Consider the following block of code:
#include <iostream>
using namespace std;
class Base {
public:
Base();
virtual void show();
};
class Derived
ublic Base {
int d;
public:
Derived();
virtual void show();
private:
};
Base::Base() {}
void Base::show(){
cout << "In show base" << endl;
}
Derived:
erived() {}
void Derived::show() {
cout << "In show derived" << endl;
}
int main()
{
// Assign a Derived * object to a Base * pointer
// Note - u cannot assign a Base * object to a Derived * ptr
Derived *d = new Derived;
Base *b = d;
if (b) {
b->show();
}
Derived **dd = &d;
(*dd)->show();
Base **bb = dd; // compilation error - why ?
}
C++ lets me assign a Derived object pointed to by a Derived * to a Base *
But a Derived object pointed to by a Derived ** cannot be initialized to a Base ** - Why ?
Derived *d = new Derived;
Base *b = d;
IS OK !!
But,
Derived **dd = &d; // Ok again
Base **bb = dd; // compilation error - why ?
Cheers
#include <iostream>
using namespace std;
class Base {
public:
Base();
virtual void show();
};
class Derived
int d;
public:
Derived();
virtual void show();
private:
};
Base::Base() {}
void Base::show(){
cout << "In show base" << endl;
}
Derived:
void Derived::show() {
cout << "In show derived" << endl;
}
int main()
{
// Assign a Derived * object to a Base * pointer
// Note - u cannot assign a Base * object to a Derived * ptr
Derived *d = new Derived;
Base *b = d;
if (b) {
b->show();
}
Derived **dd = &d;
(*dd)->show();
Base **bb = dd; // compilation error - why ?
}
C++ lets me assign a Derived object pointed to by a Derived * to a Base *
But a Derived object pointed to by a Derived ** cannot be initialized to a Base ** - Why ?
Derived *d = new Derived;
Base *b = d;
IS OK !!
But,
Derived **dd = &d; // Ok again
Base **bb = dd; // compilation error - why ?
Cheers