c++ - using a method declared pure virtual in derived classes -


this question has answer here:

i working code , saw odd, method of class "myclass" let's call x() :

virtual void x() = 0; 

so myclass abstract class , in myclass.cpp x() has proper implementation... in derived classes of myclass, method called via myclass::x();

i thought = 0 invalidate implementation... it's not case , is, in fact, usable in derived classes.

can please tell compiler when encounters = 0 ?

from standard (9.2 class members [class.mem]):

= 0 pure-specifier

it tells compiler that:

  1. the class abstract
  2. the method defined outside class definition (usually in derived class)

example 1 (build fails)

if understand question correctly, have that:

class myclass { public:     virtual void x() = 0; };  class myderivedclass : myclass { public:     virtual void x(); };  void myderivedclass::x() { myclass::x(); }  int main() {     myderivedclass mdc;     mdc.x();      return 0;     } 

if so, build should fail with:

error:

undefined reference 'myclass::x()' 

example 2 (build succeeds)

however, if method myclass::x() declared pure virtual, can provide definition. following work. class myclass still abstract, can call method myclass::x().

#include <iostream>  class myclass { public:     virtual void x() = 0; // pure virtual method };  class myderivedclass : myclass { public:     virtual void x(); };  void myclass::x() {       // pure virtual method definition     std::cout << "myclass::x()" << std::endl; }  void myderivedclass::x() {     myclass::x();     std::cout << "myderivedclass::x()" << std::endl; }    int main() {     myderivedclass mdc;     mdc.x();      return 0;     } 

output:

myclass::x() myderivedclass::x() 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -