C++ copy constructor - small but important difference -
i couldn't figure out happening here, thought strange, , after getting understand reason thought sharing answer valuable somebody's time.
so given simple code:
#include <iostream> using namespace std; class shape { public: int* a; shape(){ cout<<"default shape constructor"<<endl; = new int(8); // default } shape(int n){ = new int(n); cout<<"shape(n) constructor"<<endl; } // copy constructor shape(const shape& s){ cout<<"shape copy constructor"<<endl; = new int(*(s.a)); } shape& operator=(const shape& s){ cout<<"shape operator="<<endl; if (&s == (this)) return (*this); // this.clear(); = new int(*(s.a)); return (*this); } virtual void draw(){ cout<<"print shape number "<<*a<<endl; }; virtual ~shape(){ delete a; cout<<"shape distructor"<<endl; } }; class circle : public shape { public: int b; circle() { cout<<"default circle constructor"<<endl; b=0; } virtual void draw() { cout<<"printing circle. number "<<b<<endl; } ~circle(){ cout<<"circle distructor"<<endl; } }; why 2 following tests gives 2 different answers:
static void test1(){ shape shape = circle() ; shape.draw(); } static void test2(){ shape* shape = new circle() ; shape->draw(); delete shape; } well, because i'm getting know virtual mechanism now, figured both test produce same result (printing circle). while happens in test2 not case in test1.
to understand why, wrote happens in backround.
test1: 1. program perform line " circle() ". 1.1 call default constructor of shape made (because circle derived shape). 1.2 call default constructor of circle made.
- the program performs action " shape shape = ". calls copy constructor of shape. * here should note copy constructor not copy _vptr invisible field in circle. copies value of , returns (*this). real reason why doesn't print circle.
here have question. when ran test1 got output: default shape constructor default circle constructor shape copy constructor circle distructor shape distructor print shape number 8 shape distructor
if copy constructor signature shape(const shape& s), according output, there call copy constructor before creating shape shape. how can happen?
test2: 1. new instance of class circle being build on heap. (the line new circle performed) 2. pointer address in memory on heap returned , placed in pointer shape. in first 4 bytes of address lies pointer virtual table of circle. why test1 different test2.
it important understand the difference between test has nothing fact test1 builds circle on stack , test2 builds circle on heap. well, has it. real reason copy constructor not copy _vptr.
it's called 'slicing' class copying (non-polymorphically) base type
see thinking in c++ backgrounder
Comments
Post a Comment