Re: I need help understanding inheritance and virtual functions
On May 8, 3:14 am, dwightarmyofchampi...@hotmail.com wrote:
I compiled the program, both with and without the virtual keyowrd, but
I still don't quite get it.
Which program? It is always a good idea to keep the relevant context
of the original thread intact while you reply to it - it helps many
time.
[original thread]
class Shape{ public: virtual void draw(); };
class Rectangle: public Shape { public: virtual void draw(); };
class Triangle: public Shape { public: virtual void draw(); };
int main() {
Triangle t1, t2;
Rectangle r1, r2;
Shape* shapes[4];
shapes[0]=&t1;
shapes[1]=&r1;
shapes[2]=&t2;
shapes[3]=&r2;
}
[/end original thread]
How can the derived class override the base class's virtual draw()
function if you're defining an object of type Shape*?
You are _not_ defining an object of type Shape*. you are defining a
variable "shapes" that represents an Array of four Shape-pointers.
What is important here is to understand that the "shapes" array
doesn't itself contain Shape objects, rather it container four
pointers.
The derived
classes have things that the base classes do not (additional data
members and such), and now even though it's an object of type Shape*
(the base class), it can still behave like an object of the derived
class (i.e., accessing its derived draw() function)?
The object that is pointed by shapes[0], or shapes[1] etc is an object
of derived class. This is because we are clearly saying
shapes[0] = &t1; //t1 is a triangle object, and address of this
object is held by shapes[0]
Similarly
shapes[1] = &r1; //r1 is a rectangle object.
And if that is
the case, why not just originally define the object to be of type
Derived* in the first place?
Please understand again: Objects don't have types like "Derived*" or
"Base*" , they are the types of "pointers". Also, please note the
difference between a pointer, and an object. When we say
Shape* s = new Triangle();
We are creating an object of type Triangle (on heap), we are creating
a pointer of type Shape* (on stack) and we are putting the address of
the newly created Triangle object in the newly created Shape*
pointer.
[...]