After reading a lot about VTables, I still have one unanswered question.
Given the following class:
#include <iostream>
using namespace std;
class Shape {
public:
int* a;
Shape(){
cout<<"default Shape ctor"<<endl;
a = new int(15);
}
Shape(int n){
a = new int(n);
cout<<"Shape(n) constructor"<<endl;
}
Shape(const Shape& s){
cout<<"copy constructor"<<endl;
a = new int(*(s.a));
}
Shape& operator=(const Shape& s){
cout<<"operator="<<endl;
if (&s == (this))
return (*this);
a = new int(*(s.a));
return (*this);
}
virtual void draw(){
cout<<"print Shape the number is "<<*a<<endl;
};
virtual ~Shape(){
delete a;
cout<<"Shape distructor"<<endl;
}
};
class Circle : public Shape {
public:
int b;
Circle() {
cout<<"Circle constructor"<<endl;
b=5;
}
virtual void draw() {
cout<<"print Circle. The number is "<<b<<endl;
}
~Circle(){
cout<<"Circle distructor"<<endl;
}
};
and the following test:
static void test2(){
Circle* c = new Circle();
cout<<"size of *c is "<<sizeof(*c)<<endl;
Shape* s = c;
cout<<"size of *s is "<<sizeof(*s)<<endl;
s->draw();
}
I get this output:
default Shape ctor
Circle constructor
size of *c is 12
size of *s is 8
print Circle. The number is 5
My question is: I know how s addresses Circle :: draw, but how do I know the variable b = 5? Since this is a test show, s does not have this information. What am I missing here?
Thank!
Ok guys. Thanks for your quick answers ...
From your answers, I learned that in Circle :: draw () (* this) is of type Circle. OK. Now my question has changed: because I only wanted s to be a Shape * type, that is, in my program I only need Shape qualities. Is it possible that the next 4 bytes (the variable b in the circle) will be somehow accepted by the compiler? If so, obviously Circle :: draw () will not work properly.
, , 4 "" s?