Re: A question about complier for C++

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Fan Lu,

> Do the copy assignment operator and copy constructor in derived class
> will automatically invoke the corresponding functions in base class?

Yes and no.

YES. The C++ generated synthetic assignment operator and copy constructor in
derived classes will automatically invoke the corresponding function in the
base class.

NO.  If you provide your own assignment operator and copy constructor, you
have to invoke the corresponding functions from the base class explicitly.

> Or I need explicit invoke the A:A or A& operator= in B:B or B& operator=?

Yes and no.

YES, for your explicit ones, assuming that doing so it the "right thing to
do" for your class.

NO, for the synthesized ones (but if you are using the synthesized ones in
your derived classes, you wouldn't be able to explicitly do it anyway),
since the synthesized ones will do that for you.  (Which *MAY* be the "wrong
thing to do" in some circumstances.)

HTH,
--Eljay

#include <iostream>

using std::cout;
using std::endl;

class A
{
public:
  A() { cout << "A default constructor" << endl; }
  A(A const&) { cout << "A copy constructor" << endl; }
  A& operator=(A const&) { cout << "A assignment operator" << endl; }
};

class B : public A
{
public:
  B() { cout << "B default constructor" << endl; }
  B(B const&) { cout << "B copy constructor" << endl; }
  B& operator=(B const&) { cout << "B assignment operator" << endl; }
};

int main()
{
  cout << "----------------" << endl;
  cout << "Test copy constructor..." << endl;
  B b1;
  B b2(b1);
  cout << "----------------" << endl;
  cout << "Test assignment operator..." << endl;
  b2 = b1;
  cout << "----------------" << endl;
}


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux