-
Virtual functions help
I'm having trouble creating a B1 reference to d1. I get a compiler error saying "error C2243: 'type cast' : conversion from 'D1 *' to 'B1 &' exists, but is inaccessible". Somehow I got it to compile by making D1 a struct. I'm using Visual C++.
Code:
#include "../std_lib_facilities.h"
class B1
{
public:
virtual void vf() {cout << "B1::vf\n";}
void f() {cout << "B1::f\n";}
};
class D1 : B1
{
public:
void vf() {cout << "D1::vf\n";}
void f() {cout << "D1::f\n";}
};
int main()
{
B1 b1;
D1 d1;
b1.vf();
b1.f();
d1.vf();
d1.f();
B1& r = d1;
keep_window_open();
}
-
And if you do
Code:
class D1 : public B1
instead?
-
Unfortunately, this does not do what you think it does. This uses private inheritance, which would make all members in Base inaccessible because they're all inherited as private members.
The compiler is trying to call an operator in Base, but fails due to that it's private in the derived class. The following demonstrates that it's private inheritance:
Code:
class CBase
{
public:
CBase() { }
void myfunc() { }
};
class CDerived: CBase
{
public:
CDerived() { }
};
int main()
{
CDerived d;
d.myfunc();
return 0;
}
This gives the compile error:
Error 1 error C2247: 'CBase::myfunc' not accessible because 'CDerived' uses 'private' to inherit from 'CBase' g:\w00t\visual studio 2008\projects\test\test.cpp 17
Now, if you change it to
Code:
class CDerived: public CBase
It will compile fine.