R
Ragnar
Hello
If there a derived class privately inheriting from a base class, there
is no subtyping relationship between them. So a funtion that expects a
base class pointer should not accept a derived class pointer.
However, if this same function is called from within a derived class
function, passing 'this', then the function accepts it. Why is that. I
enclose some test code:
#include <iostream>
using std::cout;
class Base {
friend class FriendClass;
private:
virtual void print() const { cout << "In Base\n"; }
};
class FriendClass {
public:
void print(Base * pb) { pb->print(); }
};
class Derived : private Base { // note private
void print() const { cout << "In Derived 2\n"; }
public:
void printEx(FriendClass & rf, Derived * pd) {
rf.print(pd); // why does this work ?
rf.print(this); // why does this work ?
}
};
int main()
{
FriendClass of;
Derived od;
//Base * pb = new Derived; // will not work, base inaccessible
//of.print(&od); // does not work
od.printEx(of, &od); // works
return 0;
}
Here, if print is called from main, being passed &od, it does not
compile. If print is called from printEx, being passed this, it
compiles. Why ?
I used g++ 3.2.
Regards & Thanks
If there a derived class privately inheriting from a base class, there
is no subtyping relationship between them. So a funtion that expects a
base class pointer should not accept a derived class pointer.
However, if this same function is called from within a derived class
function, passing 'this', then the function accepts it. Why is that. I
enclose some test code:
#include <iostream>
using std::cout;
class Base {
friend class FriendClass;
private:
virtual void print() const { cout << "In Base\n"; }
};
class FriendClass {
public:
void print(Base * pb) { pb->print(); }
};
class Derived : private Base { // note private
void print() const { cout << "In Derived 2\n"; }
public:
void printEx(FriendClass & rf, Derived * pd) {
rf.print(pd); // why does this work ?
rf.print(this); // why does this work ?
}
};
int main()
{
FriendClass of;
Derived od;
//Base * pb = new Derived; // will not work, base inaccessible
//of.print(&od); // does not work
od.printEx(of, &od); // works
return 0;
}
Here, if print is called from main, being passed &od, it does not
compile. If print is called from printEx, being passed this, it
compiles. Why ?
I used g++ 3.2.
Regards & Thanks