Thread: Does calling a constructor from a constructor create two objects?

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    204

    Question Does calling a constructor from a constructor create two objects?

    Code:
    class Foo : public Bar {
        public: 
            Foo();
            Foo(char b);
        private:
            char x;
    };
    
    
    Foo::Foo (char b) {
        x = b;
        Foo();
    }
    
    
    Foo::Foo () {
        Bar();
    }

    Does calling Foo (3) create a second instantiation of Foo? Does calling Foo () instantiate both Foo and Bar? How about the following constructor:

    Code:
    Foo::Foo () {
        x = 'w';
    }
    Since Bar is inherited, would the above instantiate both Foo and Bar?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    How about some simple experiments?
    Code:
    #include <iostream>
    using namespace std;
    
    class Bar {
      public:
        Bar() {
          cout << "Default ctor Bar at " << this << endl;
        }
    };
    
    class Foo : public Bar {
        public: 
            Foo();
            Foo(char b);
        private:
            char x;
    };
     
     
    Foo::Foo (char b) {
        cout << "Param   ctor Foo at " << this << endl;
        x = b;
        Foo();
    }
     
     
    Foo::Foo () {
        cout << "Default ctor Foo at " << this << endl;
        Bar();
    }
    
    int main ( ) {
      Foo x('c');
    }
    Add traces for say
    - the start and end of functions
    - the destructors
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    204
    I had not thought of a good way to test that. It looks like explicitly calling a constructor always instantiates an object, while inheriting a class does not.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    When a class inherits another, both the derived and base class constructors are called. But no constructor is called unless you create an instance of an object.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Calling a constructor within the body of another function will create a temporary just like it would in any other function. However, C++11 supports delegating constructors, wherein you can call a constructor in the initialiser list of another constructor, which will execute that delegated constructor on the same object, before allowing the constructor body to run. Likewise, you can call base cass constructors with simmilar syntax. For example:
    Code:
    struct Foo{
      Foo():Foo{""}{
        std::cout << "Default construct foo at " << this << "\n"; 
      }
      Foo(std::string str){ 
        std::cout <<"Constuct Foo with \"" <<str << "\" at " << this << "\n";
      }
    };
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    Registered User
    Join Date
    Jan 2017
    Posts
    6
    Does calling a constructor from a constructor create two objects? Yes.

    Extra information that may help:
    The base constructor is always called before derived constructor and destructors are called in the opposite order (derived first).

    Code:
    class A {};
    class B : public A {};
    class C : public B {};
    When you create an instance of C, constructor of A is called followed by B and then C. When the instance is destroyed, the destructor of C is called followed by B and finally A. This order is important. Anything you do inside constructors does not effect the overall order. (Of course if you create an instance of A inside constructor of B then it may seem like the compiler isn't respecting this order but technically it's still the same order.)

    As Salem has said, a good approach to understanding this is to add print statements to constructors and destructors. Two individual objects are guaranteed to have different memory address so you can print addresses as well to help you.

    Sometimes your class has multiple constructors and you want to call two or more of them. Before C++11 there wasn't a nice way of doing this, you had to move code from constructors to methods and call them instead. As King Mir has mentioned C++11 lets you delegate constructors.

    Code:
    class A {
    public:
        A() {
            std::cout << "A()\n";
        }
    };
    
    class B : public A {
    public:
        B() : B(10) {
            std::cout << "B()\n";
            // B(10); // this will mostly likely do something you're not expecting, a temporary instance of B will be created, value of x is indeterminate
        }
    
        B(int i) : x(i) {
            std::cout << "B(int)\n";
            std::cout << "x is " << x << "\n";
        }
    
    
    private:
        int x;
    };
    The output when you create B instance:
    Code:
    A()
    B(int)
    x is 10
    B()
    So the constructor of the base class is always called first which is good.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Constructor calling constructor: SIGSEGV
    By Benji Wiebe in forum C++ Programming
    Replies: 10
    Last Post: 08-30-2012, 04:12 AM
  2. Replies: 5
    Last Post: 02-21-2011, 02:19 AM
  3. Calling other objects methods inside a constructor
    By mynickmynick in forum C++ Programming
    Replies: 5
    Last Post: 09-17-2008, 06:31 AM
  4. Replies: 10
    Last Post: 06-02-2008, 08:09 AM
  5. Constructor calling another constructor
    By renanmzmendes in forum C++ Programming
    Replies: 4
    Last Post: 03-21-2008, 03:51 PM

Tags for this Thread