VTable and polymorphism

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); // default
    }
    Shape(int n){
        a = new int(n);
          cout<<"Shape(n) constructor"<<endl;
    }
    // copy constructor
    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);
//      this.clear();
        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?

+5
4

, , , s Circle - Circle b. s->draw();, Circle::draw(), , Circle::draw() *this (.. ) Circle not Shape. , Circle::draw() b.

EDIT: s Shape - , , ( Circle ), (Shape* Circle*). Circle , . Circle - s , Shape*, , - s, Circle, .. s->draw(); Circle::draw. , Circle Shape* Circle - "", b. , :

Circle c;
Shape s = c; // copies the Shape data members across from c, but slices off the rest
+2
  • sizeof . , s; , s Shape Shape. ; , , s Circle. *s Circle, , , sizeof(Circle), , , .

  • s , , Shape. draw - Shape, - , , - " draw(), ". a Circle* Circle::draw - . Circle, b Shape ( Circle , ).

+1

, s Circle, draw Circle. Circle Circle. , Circle:: draw, "" , Circle

0

sizeof() . *s Shape. s Circle, , , overriden draw(), b, Circle. , sizeof() .

typeid(), , . .

0

All Articles