This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: C++ base class constructor not called


Tom Harkness <th@geomec5.civil.soton.ac.uk> writes:

>   This message is in MIME format.  The first part should be readable text,
>   while the remaining parts are likely unreadable without MIME-aware tools.
>   Send mail to mime@docserver.cac.washington.edu for more info.
> 
> --1318606433-1525996441-949234199=:6559
> Content-Type: TEXT/PLAIN; charset=US-ASCII
> 
> Transcript:
> 
> $ g++ -v
> Reading specs from /usr/local/lib/gcc-lib/i586-pc-linux-gnu/2.95.2/specs
> gcc version 2.95.2 19991024 (release)
> $ g++ -o bug1 bug1.C
> $ bug1
> construct 0xbffffcdc
> destroy   0x8058728
> destroy   0xbffffcdc
> 
> Surely the base class constructor should always be called, even if the copy
> constructor of the derived class is implicitly defined.  Isn't this a bug?
> (By explicitly defining an empty copy constructor, B(const B &b) { }, the
> problem vanishes.)

> 
> #include <iostream>
> 
> class A
> {
> public:
>         A() { std::cout << "construct " << this << "\n"; }
>         virtual ~A() { std::cout << "destruct  " << this << "\n"; }

Since you did not create a copy constructor for A, the compiler will
  create one for you.

> };
> 
> class B : public A
> {
> public:
>         B() { }
>         B *clone() const { return new B(*this); }
> };
> 
> int main()
> {
>         B b;
>         A *bb = b.clone();
>         delete bb;
>         return 0;
> }

A compiler-generated copy constructor will call the copy constructors
  of the class's base classes. So B's copy constructor will look
  something like this:

B::(B const& rhs)
  :A(rhs)
{}

The closest match for A(B const&) is A::A(A const&) ... which is A's
  compiler generated copy constructor.

However, if you define:

B::B(B const&){}

A's default constructor will be called, as no other constructor was
  specified.

So I don't think this is a bug.

By the way, it is still good to send bug reports, even if there are
  bugs in the bug reports. :-)

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]