Alex Rivera | Logout

Adding virtual removes the error : type 'base' is not a direct base of derived class

Asked 2011-12-07T16:49:13.630
9

Conside the following sample code below:

#include <iostream>

using namespace std;

class base
{
   public:
      base()
      {
         cout << "ctor in base class\n";
      }
};

class derived1 : public base
{
   public:
      derived1()
      {
         cout <<"ctor in derived1 class\n";
      }
};

class derived2 : public derived1
{
   public:
      derived2() : base()
      {
         cout << "ctor in derived2 class\n";
      }
};

int main()
{
   derived2 d2obj;
   return 0;
}

This gives the error:

error: type `base' is not a direct base of `derived2'

Why is this error occurring? If i make the base class virtual, the error is no longer there. What is the reason for this?

Edit
Report

1 Answer

5

Change

class derived2 : public derived1
{
   public:
      derived2() : base()
      {
         cout << "ctor in derived2 class\n";
      }
};

to

class derived2 : public derived1
{
   public:
      derived2() : derived1()
      {
         cout << "ctor in derived2 class\n";
      }
};

This is because you trying to call base1 constructor from a grand child derived2.

If you change the derivation of derived1 from base1 to be virtual. It is ok to call base1 from derived2. More details here.

answered 2011-12-07T16:53:19.783

Your Answer