-4

I have a base class A and two classes B, C derived from A. Declaration of method func is given in class A. How can I define method func separately for B and C ?

class A {
public:
   void func();
};

class B : public A {
//some members
};

class C : public A {
//some members
};

//define B's func here without changing the definition of the three classes
//define C's func here without changing the definition of the three classes
newuser
  • 129
  • 1
  • 1
  • 8
  • 2
    This is a _very_ basic topic in C++ and is covered in books on C++. I suggest you pick up a [good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Captain Obvlious Apr 29 '16 at 21:06
  • Not possible without using "virtual" directive. The address of A::func() has to be overwritten by B::func() or C::func() and can only be done if we do late binding. – Vink Apr 29 '16 at 21:17

2 Answers2

2

You have to make the method you want to overwrite "virtual" or "pure virtual" and if a class has virtual methods, also the destructor must be virtual:

class A {
public:
  virtual ~A{};
  virtual void func() = 0;
};

class B : public A {
  void func() {};
};

class C : public A {
  void func() {};
};
cwschmidt
  • 1,194
  • 11
  • 17
2

No, you cannot implement a member function for a class without it being declared in the class.

class A {
public:
   void func();
};

class B : public A {
//some members
};

class C : public A {
//some members
};

void B::func() {}
void C::func() {}
/tmp/164435074/main.cpp:17:9: error: out-of-line definition of 'func' does not match any declaration in 'B'
void B::func() {}
        ^~~~
/tmp/164435074/main.cpp:18:9: error: out-of-line definition of 'func' does not match any declaration in 'C'
void C::func() {}
        ^~~~
kmdreko
  • 42,554
  • 6
  • 57
  • 106