G
garyolsen
Case 1:
==============
class MyClass
{
public:
virtual void MyVirt();
};
class MyChildClass : public MyClass
{
public:
void MyVirt();
};
If MyClass contains a virtual function which will be overridden by it
children classes:
MyChildClass *MChildC = new MyChildClass();
MyClass* ptr = MChildC;
ptr->MyVirt();//MyChildClass::MyVirt() called
Otherwise, the overriding function, MyVirt(), in MyChildClass will not be
executed?
Everything fine. Please read on...
Case 2:
=============
The same two classes as in Case 1.
MyChildClass MCC;
MyClass* ptr = &MCC;
ptr->MyVirt();
Will the staement, ptr->MyVirt(), actually call MyChildClass::MyVirt()?
Is this a general practice of polymorphism in C++ like in Case 1?
Now, this leads me to another question:
Why such a "Pointer"/"Reference" requirement needed to cause a late binding?
Case 3:
==============
Now we make some changes for the above two classes:
class MyClass
{
public:
void MyNonVirt() { MyVirt(); }
private:
virtual void MyVirt();
};
class MyChildClass : public MyClass
{
private:
void MyVirt();
};
Note that MyNonVirt() calls MyVirt() and MyVirt() is private member now.
First, is this a good design at all?
How should I do to make sue that MyChildClass::MyVirt() is called at
runtime?
Thanks!
==============
class MyClass
{
public:
virtual void MyVirt();
};
class MyChildClass : public MyClass
{
public:
void MyVirt();
};
If MyClass contains a virtual function which will be overridden by it
children classes:
MyChildClass *MChildC = new MyChildClass();
MyClass* ptr = MChildC;
ptr->MyVirt();//MyChildClass::MyVirt() called
Otherwise, the overriding function, MyVirt(), in MyChildClass will not be
executed?
Everything fine. Please read on...
Case 2:
=============
The same two classes as in Case 1.
MyChildClass MCC;
MyClass* ptr = &MCC;
ptr->MyVirt();
Will the staement, ptr->MyVirt(), actually call MyChildClass::MyVirt()?
Is this a general practice of polymorphism in C++ like in Case 1?
Now, this leads me to another question:
Why such a "Pointer"/"Reference" requirement needed to cause a late binding?
Case 3:
==============
Now we make some changes for the above two classes:
class MyClass
{
public:
void MyNonVirt() { MyVirt(); }
private:
virtual void MyVirt();
};
class MyChildClass : public MyClass
{
private:
void MyVirt();
};
Note that MyNonVirt() calls MyVirt() and MyVirt() is private member now.
First, is this a good design at all?
How should I do to make sue that MyChildClass::MyVirt() is called at
runtime?
Thanks!