By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,130 Members | 1,365 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,130 IT Pros & Developers. It's quick & easy.

inherit assigment operator

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
yopwojtek wrote in news:1122137091.534825.212870
@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.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #2

P: n/a
thanks a lot.
woyt

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.