0

I am trying to implement a contract class in Borland C++ Builder, but get a compilation error that I do not understand. The code looks like:

class baseClass2 {
  public:
    virtual void test () = 0;
};

class derivedClass: public baseClass2 {
  derivedClass () {test ();};
};

void baseClass2::test () {

};

ant it compiles, but I believe that

void baseClass2::test ()
should be in the derived class. If I put it here, I get

[C++ Error] multiple_inheritance.cpp(33): E2316 'derivedClass::test()' is not a member of 'derivedClass'

Why am I getting this? Thanks!

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56

3 Answers3

0

void baseClass2::test ()

This is incorrect since you have already declared test() as a virtual function in baseClass2.

should be in the derived class

Before you do that, you should declare it in the derivedClass definition as follows:

class derivedClass: public baseClass2 {
public:
    derivedClass () {test ();};
    virtual void test();
};

void derivedClass:test() {

}

Then you can call test() in your derived class constructor.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

the base class implementation of test() is pure-virtual. It's legal to provide an implementation in your base class, but you must still provide another one in your derived class as well (assuming that you want derivedClass to be a concrete class).

class baseClass2 {
public:
    virtual void test () = 0;
};

class derivedClass: public baseClass2  {
public:
    derivedClass() { test(); }
    void test();
};

void baseClass2::test () {
}

void derivedClass::test () {
} 
Ben Cottrell
  • 5,741
  • 1
  • 27
  • 34
0

This is quite subtle. If your derived constructor should call a function that was declared virtual in one of your ancestor classes (whether directly, or via another member function (so can be quite hard to spot)), then you will call the implementation in the base class. This happens even if you have overridden the virtual function.

This means that in your case derivedClass::derivedClass() will therefore call the pure virtial baseClass2::test(). Eeek!

Yes, this is how C++ works. The derived vtable pointer points to the base class vtable while you are in the constructor. It is only updated one you leave the constructor.

bobbogo
  • 14,989
  • 3
  • 48
  • 57