inherit assigment operator

Y

yopwojtek

Hello All,
i know from some tutorials, that copy constructor and assigment
operator is not inherited from base to derived class. i think it make
sense but i wrote a little example:

class Base {
protected:
int* a_;
public:
Base& operator=(const Base& _toCopy) {
*a_ = 5;
return *this;
}
Base() : a_(new int(6)) {}
~Base() {delete a_;}

int GetAValue() {return *a_;}
};

class Derive : public Base {
private:
double b_;
public:
Derive() : Base(), b_(1.0) {*a_ = 7;}
};

int _tmain() {
Derive der1;
Derive der2;
der1 = der2;
cout << der1.GetAValue() << endl; // - here got 5 on screen

return 0;
}

and i.m confused, becouse my assigment operator works for object from
derive class:( why?? I thought that der1 = der2; will use default
assigment operator generated by compiller. but is used the one from
Base class becouse i see that der1,GetAValue() return 5.
I hope You will able to explain me why it is so. The compiller is
VC++7.0.
thanks for any answers.
yopwojtek
czyli tworze zupelnie bzdurny operator przypisania z kopiowaniem w
klasie Base (w zasadzie nie kopiuje tylko ustawia *a_ na 5), ale nie
tworze go w klasie Derive. natomiast jesli teraz zastosuje operator
przypisania dla obiektów klasy pochodnej, to widac, ze jednak
zostanie zastosowany nie wygenerowany przez kompilator operator
domyslny tylko wlasnie ten który zdefiniowalem w klasie Base,
czyli jednak podczas dziedziczenia zostal przekazany do klasy Derive.
nie rozumiem dlaczego tak sie dzieje, bardzo prosze o razjasnienie
mi problemu?? kompilator to VC++7.0
pozdrawiam
woyt
 
R

Rob Williscroft

yopwojtek wrote in @g44g2000cwa.googlegroups.com in comp.lang.c++:
and i.m confused, becouse my assigment operator works for object from
derive class:( why?? I thought that der1 = der2; will use default
assigment operator generated by compiller. but is used the one from
Base class becouse i see that der1,GetAValue() return 5.
I hope You will able to explain me why it is so. The compiller is
VC++7.0.

The compiler generated assignment operator, just calls operator = ()
for each sub-objects, this means base classes and member variables.

So the compiler generated operator = () in derived is calling your
user defined operator = ().

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top