M
Marcelo De Brito
Hi!
Can I use a base class as a generic interface for manipulation of
derived classes from it?
I have noticed that even classes that do not inherit "directly" from
the base class can be manipulated through a base class pointer, of
course taking into account all the virtual stuffs are done properly.
For example:
class B1 {
public:
B1() {}
virtual ~B1() {}
virtual void f() {}
};
class D1 : public B1{
public:
D1() {}
virtual ~D1() {}
void f() {}
};
class D2 : public D1{
public:
D2() {}
virtual ~D2() {}
void f() {}
};
int main()
{
D2 dd2;
B1* bb1 = &dd2;
//OR B1* bb1 = new D2;
bb1->f(); //calls D2's "f()" function
}
From what I have tested so far, all the public methods inside D2 can
be manipulated through the "B1" pointer "bb1", even though both
classes does not have a "direct" relationship (I know they have
through D2).
What kinds of problems can arise from that approach? What about the
safety of using it? Is it safe?
I apprecite any comment, suggestion, etc.
Thank You!
Marcelo
Can I use a base class as a generic interface for manipulation of
derived classes from it?
I have noticed that even classes that do not inherit "directly" from
the base class can be manipulated through a base class pointer, of
course taking into account all the virtual stuffs are done properly.
For example:
class B1 {
public:
B1() {}
virtual ~B1() {}
virtual void f() {}
};
class D1 : public B1{
public:
D1() {}
virtual ~D1() {}
void f() {}
};
class D2 : public D1{
public:
D2() {}
virtual ~D2() {}
void f() {}
};
int main()
{
D2 dd2;
B1* bb1 = &dd2;
//OR B1* bb1 = new D2;
bb1->f(); //calls D2's "f()" function
}
From what I have tested so far, all the public methods inside D2 can
be manipulated through the "B1" pointer "bb1", even though both
classes does not have a "direct" relationship (I know they have
through D2).
What kinds of problems can arise from that approach? What about the
safety of using it? Is it safe?
I apprecite any comment, suggestion, etc.
Thank You!
Marcelo