What are the rules for calling the superclass constructor?












608















What are the C++ rules for calling the superclass constructor from a subclass one?



For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).










share|improve this question




















  • 6





    Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

    – andreee
    Jun 11 '18 at 12:44
















608















What are the C++ rules for calling the superclass constructor from a subclass one?



For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).










share|improve this question




















  • 6





    Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

    – andreee
    Jun 11 '18 at 12:44














608












608








608


204






What are the C++ rules for calling the superclass constructor from a subclass one?



For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).










share|improve this question
















What are the C++ rules for calling the superclass constructor from a subclass one?



For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).







c++ inheritance constructor






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 8 '17 at 8:35









Melebius

3,08532235




3,08532235










asked Sep 23 '08 at 13:09









leviklevik

73.4k236689




73.4k236689








  • 6





    Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

    – andreee
    Jun 11 '18 at 12:44














  • 6





    Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

    – andreee
    Jun 11 '18 at 12:44








6




6





Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

– andreee
Jun 11 '18 at 12:44





Just nitpicking: There is no "super class" in C++, in fact, the standard does not mention it at all. This wording stems from Java (most probably). Use "base class" in C++. I guess that super implies a single parent, while C++ allows for multiple inheritance.

– andreee
Jun 11 '18 at 12:44












9 Answers
9






active

oldest

votes


















825














Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".



class SuperClass
{
public:

SuperClass(int foo)
{
// do something with foo
}
};

class SubClass : public SuperClass
{
public:

SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};


More info on the constructor's initialization list here and here.






share|improve this answer





















  • 46





    I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

    – luke
    Sep 24 '08 at 12:38






  • 1





    the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

    – ha9u63ar
    Oct 31 '14 at 9:33






  • 2





    @hagubear, only valid for constructors, AFAIK

    – luke
    Oct 31 '14 at 12:24











  • When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

    – LazerSharks
    Nov 24 '14 at 1:49








  • 2





    @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

    – luke
    Nov 24 '14 at 2:27



















214














In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:



class Sub : public Base
{
Sub(int x, int y)
: Base(x), member(y)
{
}
Type member;
};


If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:



class Sub : public Base
{
Sub(int x, int y)
try : Base(x), member(y)
{
// function body goes here
} catch(const ExceptionType &e) {
throw kaboom();
}
Type member;
};


In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.






share|improve this answer





















  • 1





    I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

    – levik
    Sep 23 '08 at 13:47






  • 2





    Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

    – puetzk
    Sep 23 '08 at 15:55






  • 96





    Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

    – jakar
    Jun 8 '12 at 17:23






  • 17





    I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

    – Cameron
    Nov 21 '13 at 1:29











  • I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

    – peterk
    Jan 16 at 15:28



















47














In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:




class A : public B
{
public:
A(int a, int b, int c);
private:
int b_, c_;
};


Then, assuming B has a constructor which takes an int, A's constructor may look like this:




A::A(int a, int b, int c)
: B(a), b_(b), c_(c) // initialization list
{
// do something
}


As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.



Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.






share|improve this answer



















  • 1





    Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

    – levik
    Sep 23 '08 at 13:39






  • 5





    Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

    – Dima
    Sep 23 '08 at 13:44






  • 1





    And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

    – Dima
    Sep 23 '08 at 13:44






  • 2





    This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

    – Benjamin
    Nov 11 '14 at 17:17






  • 1





    Too bad i can give only one upvote for this !!! Excellent answer

    – Rajesh
    Sep 30 '16 at 8:59



















20














Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example.
The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).






share|improve this answer





















  • 10





    This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

    – Richard Chambers
    Apr 19 '14 at 13:22











  • @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

    – TT_
    Apr 19 '14 at 23:56



















19














The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.



Class2::Class2(string id) : Class1(id) {
....
}


Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.






share|improve this answer

































    19














    If you have a constructor without arguments it will be called before the derived class constructor gets executed.



    If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:



    class base
    {
    public:
    base (int arg)
    {
    }
    };

    class derived : public base
    {
    public:
    derived () : base (number)
    {
    }
    };


    You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.






    share|improve this answer

































      11














      If you have default parameters in your base constructor the base class will be called automatically.



      using namespace std;

      class Base
      {
      public:
      Base(int a=1) : _a(a) {}

      protected:
      int _a;
      };

      class Derived : public Base
      {
      public:
      Derived() {}

      void printit() { cout << _a << endl; }
      };

      int main()
      {
      Derived d;
      d.printit();
      return 0;
      }


      Output is: 1






      share|improve this answer
























      • This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

        – underscore_d
        Feb 10 '16 at 23:21





















      9














      CDerived::CDerived()
      : CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
      {
      //construct body
      }





      share|improve this answer































        6














        Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.






        share|improve this answer





















        • 2





          If nobody talked about it, where was it mentioned?

          – user207421
          Feb 12 '15 at 9:36






        • 3





          @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

          – darth_coder
          Feb 12 '15 at 10:41











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f120876%2fwhat-are-the-rules-for-calling-the-superclass-constructor%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        9 Answers
        9






        active

        oldest

        votes








        9 Answers
        9






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        825














        Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".



        class SuperClass
        {
        public:

        SuperClass(int foo)
        {
        // do something with foo
        }
        };

        class SubClass : public SuperClass
        {
        public:

        SubClass(int foo, int bar)
        : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
        {
        // do something with bar
        }
        };


        More info on the constructor's initialization list here and here.






        share|improve this answer





















        • 46





          I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

          – luke
          Sep 24 '08 at 12:38






        • 1





          the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

          – ha9u63ar
          Oct 31 '14 at 9:33






        • 2





          @hagubear, only valid for constructors, AFAIK

          – luke
          Oct 31 '14 at 12:24











        • When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

          – LazerSharks
          Nov 24 '14 at 1:49








        • 2





          @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

          – luke
          Nov 24 '14 at 2:27
















        825














        Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".



        class SuperClass
        {
        public:

        SuperClass(int foo)
        {
        // do something with foo
        }
        };

        class SubClass : public SuperClass
        {
        public:

        SubClass(int foo, int bar)
        : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
        {
        // do something with bar
        }
        };


        More info on the constructor's initialization list here and here.






        share|improve this answer





















        • 46





          I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

          – luke
          Sep 24 '08 at 12:38






        • 1





          the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

          – ha9u63ar
          Oct 31 '14 at 9:33






        • 2





          @hagubear, only valid for constructors, AFAIK

          – luke
          Oct 31 '14 at 12:24











        • When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

          – LazerSharks
          Nov 24 '14 at 1:49








        • 2





          @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

          – luke
          Nov 24 '14 at 2:27














        825












        825








        825







        Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".



        class SuperClass
        {
        public:

        SuperClass(int foo)
        {
        // do something with foo
        }
        };

        class SubClass : public SuperClass
        {
        public:

        SubClass(int foo, int bar)
        : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
        {
        // do something with bar
        }
        };


        More info on the constructor's initialization list here and here.






        share|improve this answer















        Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".



        class SuperClass
        {
        public:

        SuperClass(int foo)
        {
        // do something with foo
        }
        };

        class SubClass : public SuperClass
        {
        public:

        SubClass(int foo, int bar)
        : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
        {
        // do something with bar
        }
        };


        More info on the constructor's initialization list here and here.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 8 '12 at 18:44

























        answered Sep 23 '08 at 13:18









        lukeluke

        27.7k65277




        27.7k65277








        • 46





          I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

          – luke
          Sep 24 '08 at 12:38






        • 1





          the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

          – ha9u63ar
          Oct 31 '14 at 9:33






        • 2





          @hagubear, only valid for constructors, AFAIK

          – luke
          Oct 31 '14 at 12:24











        • When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

          – LazerSharks
          Nov 24 '14 at 1:49








        • 2





          @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

          – luke
          Nov 24 '14 at 2:27














        • 46





          I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

          – luke
          Sep 24 '08 at 12:38






        • 1





          the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

          – ha9u63ar
          Oct 31 '14 at 9:33






        • 2





          @hagubear, only valid for constructors, AFAIK

          – luke
          Oct 31 '14 at 12:24











        • When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

          – LazerSharks
          Nov 24 '14 at 1:49








        • 2





          @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

          – luke
          Nov 24 '14 at 2:27








        46




        46





        I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

        – luke
        Sep 24 '08 at 12:38





        I removed 'explicit' from the SuperClass constructor. Despite being a best practice for single-argument constructors, it wasn't germane to the discussion at hand. For more info on the explicit key word, see: weblogs.asp.net/kennykerr/archive/2004/08/31/…

        – luke
        Sep 24 '08 at 12:38




        1




        1





        the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

        – ha9u63ar
        Oct 31 '14 at 9:33





        the colon : operator you used to invoke superclass constructor before instantiating child class constructor, I suppose this is also true for methods?

        – ha9u63ar
        Oct 31 '14 at 9:33




        2




        2





        @hagubear, only valid for constructors, AFAIK

        – luke
        Oct 31 '14 at 12:24





        @hagubear, only valid for constructors, AFAIK

        – luke
        Oct 31 '14 at 12:24













        When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

        – LazerSharks
        Nov 24 '14 at 1:49







        When you instantiate a SubClass object by, say, SubClass anObject(1,2), does 1 then get passed to SuperClass(foo) (becomes the argument to paramater foo)? I have been searching through docs high and low, but none definitively state that the arguments to the SubClass constructor can be passed as arguments to the SuperClass constructor.

        – LazerSharks
        Nov 24 '14 at 1:49






        2




        2





        @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

        – luke
        Nov 24 '14 at 2:27





        @Gnuey, notice the : SuperClass(foo) portion. foo is explicitly being passed to the super class's constructor.

        – luke
        Nov 24 '14 at 2:27













        214














        In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:



        class Sub : public Base
        {
        Sub(int x, int y)
        : Base(x), member(y)
        {
        }
        Type member;
        };


        If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:



        class Sub : public Base
        {
        Sub(int x, int y)
        try : Base(x), member(y)
        {
        // function body goes here
        } catch(const ExceptionType &e) {
        throw kaboom();
        }
        Type member;
        };


        In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.






        share|improve this answer





















        • 1





          I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

          – levik
          Sep 23 '08 at 13:47






        • 2





          Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

          – puetzk
          Sep 23 '08 at 15:55






        • 96





          Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

          – jakar
          Jun 8 '12 at 17:23






        • 17





          I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

          – Cameron
          Nov 21 '13 at 1:29











        • I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

          – peterk
          Jan 16 at 15:28
















        214














        In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:



        class Sub : public Base
        {
        Sub(int x, int y)
        : Base(x), member(y)
        {
        }
        Type member;
        };


        If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:



        class Sub : public Base
        {
        Sub(int x, int y)
        try : Base(x), member(y)
        {
        // function body goes here
        } catch(const ExceptionType &e) {
        throw kaboom();
        }
        Type member;
        };


        In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.






        share|improve this answer





















        • 1





          I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

          – levik
          Sep 23 '08 at 13:47






        • 2





          Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

          – puetzk
          Sep 23 '08 at 15:55






        • 96





          Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

          – jakar
          Jun 8 '12 at 17:23






        • 17





          I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

          – Cameron
          Nov 21 '13 at 1:29











        • I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

          – peterk
          Jan 16 at 15:28














        214












        214








        214







        In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:



        class Sub : public Base
        {
        Sub(int x, int y)
        : Base(x), member(y)
        {
        }
        Type member;
        };


        If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:



        class Sub : public Base
        {
        Sub(int x, int y)
        try : Base(x), member(y)
        {
        // function body goes here
        } catch(const ExceptionType &e) {
        throw kaboom();
        }
        Type member;
        };


        In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.






        share|improve this answer















        In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:



        class Sub : public Base
        {
        Sub(int x, int y)
        : Base(x), member(y)
        {
        }
        Type member;
        };


        If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:



        class Sub : public Base
        {
        Sub(int x, int y)
        try : Base(x), member(y)
        {
        // function body goes here
        } catch(const ExceptionType &e) {
        throw kaboom();
        }
        Type member;
        };


        In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 1 '16 at 18:50









        Segfault

        5,70422242




        5,70422242










        answered Sep 23 '08 at 13:22









        puetzkpuetzk

        8,91631929




        8,91631929








        • 1





          I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

          – levik
          Sep 23 '08 at 13:47






        • 2





          Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

          – puetzk
          Sep 23 '08 at 15:55






        • 96





          Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

          – jakar
          Jun 8 '12 at 17:23






        • 17





          I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

          – Cameron
          Nov 21 '13 at 1:29











        • I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

          – peterk
          Jan 16 at 15:28














        • 1





          I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

          – levik
          Sep 23 '08 at 13:47






        • 2





          Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

          – puetzk
          Sep 23 '08 at 15:55






        • 96





          Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

          – jakar
          Jun 8 '12 at 17:23






        • 17





          I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

          – Cameron
          Nov 21 '13 at 1:29











        • I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

          – peterk
          Jan 16 at 15:28








        1




        1





        I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

        – levik
        Sep 23 '08 at 13:47





        I'm not sure I understand the syntax of your second example... Is the try/catch construct a replacement for the constructor body?

        – levik
        Sep 23 '08 at 13:47




        2




        2





        Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

        – puetzk
        Sep 23 '08 at 15:55





        Yes. I've reworded the section, and fixed a mistake (the try keyword goes before the initialization list). I should have looked it up instead of writing from memory, it's not something that gets used often :-)

        – puetzk
        Sep 23 '08 at 15:55




        96




        96





        Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

        – jakar
        Jun 8 '12 at 17:23





        Thanks for including the try/catch syntax for the initializers. I've been using C++ for 10 years, and this is the first time I've ever seen that.

        – jakar
        Jun 8 '12 at 17:23




        17




        17





        I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

        – Cameron
        Nov 21 '13 at 1:29





        I got to admit, been using C++ a long time, and that is the first time I have seen that try/catcn on the constructor list.

        – Cameron
        Nov 21 '13 at 1:29













        I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

        – peterk
        Jan 16 at 15:28





        I might say the function body "goes in" the try block - this way any body following the initializers will will have it's exceptions caught as well.

        – peterk
        Jan 16 at 15:28











        47














        In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:




        class A : public B
        {
        public:
        A(int a, int b, int c);
        private:
        int b_, c_;
        };


        Then, assuming B has a constructor which takes an int, A's constructor may look like this:




        A::A(int a, int b, int c)
        : B(a), b_(b), c_(c) // initialization list
        {
        // do something
        }


        As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.



        Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.






        share|improve this answer



















        • 1





          Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

          – levik
          Sep 23 '08 at 13:39






        • 5





          Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

          – Dima
          Sep 23 '08 at 13:44






        • 1





          And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

          – Dima
          Sep 23 '08 at 13:44






        • 2





          This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

          – Benjamin
          Nov 11 '14 at 17:17






        • 1





          Too bad i can give only one upvote for this !!! Excellent answer

          – Rajesh
          Sep 30 '16 at 8:59
















        47














        In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:




        class A : public B
        {
        public:
        A(int a, int b, int c);
        private:
        int b_, c_;
        };


        Then, assuming B has a constructor which takes an int, A's constructor may look like this:




        A::A(int a, int b, int c)
        : B(a), b_(b), c_(c) // initialization list
        {
        // do something
        }


        As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.



        Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.






        share|improve this answer



















        • 1





          Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

          – levik
          Sep 23 '08 at 13:39






        • 5





          Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

          – Dima
          Sep 23 '08 at 13:44






        • 1





          And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

          – Dima
          Sep 23 '08 at 13:44






        • 2





          This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

          – Benjamin
          Nov 11 '14 at 17:17






        • 1





          Too bad i can give only one upvote for this !!! Excellent answer

          – Rajesh
          Sep 30 '16 at 8:59














        47












        47








        47







        In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:




        class A : public B
        {
        public:
        A(int a, int b, int c);
        private:
        int b_, c_;
        };


        Then, assuming B has a constructor which takes an int, A's constructor may look like this:




        A::A(int a, int b, int c)
        : B(a), b_(b), c_(c) // initialization list
        {
        // do something
        }


        As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.



        Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.






        share|improve this answer













        In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:




        class A : public B
        {
        public:
        A(int a, int b, int c);
        private:
        int b_, c_;
        };


        Then, assuming B has a constructor which takes an int, A's constructor may look like this:




        A::A(int a, int b, int c)
        : B(a), b_(b), c_(c) // initialization list
        {
        // do something
        }


        As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.



        Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 23 '08 at 13:34









        DimaDima

        33.7k1260108




        33.7k1260108








        • 1





          Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

          – levik
          Sep 23 '08 at 13:39






        • 5





          Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

          – Dima
          Sep 23 '08 at 13:44






        • 1





          And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

          – Dima
          Sep 23 '08 at 13:44






        • 2





          This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

          – Benjamin
          Nov 11 '14 at 17:17






        • 1





          Too bad i can give only one upvote for this !!! Excellent answer

          – Rajesh
          Sep 30 '16 at 8:59














        • 1





          Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

          – levik
          Sep 23 '08 at 13:39






        • 5





          Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

          – Dima
          Sep 23 '08 at 13:44






        • 1





          And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

          – Dima
          Sep 23 '08 at 13:44






        • 2





          This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

          – Benjamin
          Nov 11 '14 at 17:17






        • 1





          Too bad i can give only one upvote for this !!! Excellent answer

          – Rajesh
          Sep 30 '16 at 8:59








        1




        1





        Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

        – levik
        Sep 23 '08 at 13:39





        Wait a second... You say initializers save on the cost of assignments. But don't the same assignments take place inside them if called?

        – levik
        Sep 23 '08 at 13:39




        5




        5





        Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

        – Dima
        Sep 23 '08 at 13:44





        Nope. Init and assignment are different things. When a constructor is called, it will try to initialize every data member with whatever it thinks is the default value. In the init list you get to supply default values. So you incur initialization cost in either case.

        – Dima
        Sep 23 '08 at 13:44




        1




        1





        And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

        – Dima
        Sep 23 '08 at 13:44





        And if you use assignment inside the body, then you incur the initialization cost anyway, and then the cost of assignment on top of that.

        – Dima
        Sep 23 '08 at 13:44




        2




        2





        This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

        – Benjamin
        Nov 11 '14 at 17:17





        This answer was helpful because it showed the syntax variant where one has a header and a source file, and one does not want the initialization list in the header. Very helpful thank you.

        – Benjamin
        Nov 11 '14 at 17:17




        1




        1





        Too bad i can give only one upvote for this !!! Excellent answer

        – Rajesh
        Sep 30 '16 at 8:59





        Too bad i can give only one upvote for this !!! Excellent answer

        – Rajesh
        Sep 30 '16 at 8:59











        20














        Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example.
        The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).






        share|improve this answer





















        • 10





          This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

          – Richard Chambers
          Apr 19 '14 at 13:22











        • @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

          – TT_
          Apr 19 '14 at 23:56
















        20














        Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example.
        The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).






        share|improve this answer





















        • 10





          This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

          – Richard Chambers
          Apr 19 '14 at 13:22











        • @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

          – TT_
          Apr 19 '14 at 23:56














        20












        20








        20







        Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example.
        The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).






        share|improve this answer















        Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example.
        The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 23 '17 at 12:26









        Community

        11




        11










        answered Jan 27 '14 at 22:04









        TT_TT_

        92321424




        92321424








        • 10





          This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

          – Richard Chambers
          Apr 19 '14 at 13:22











        • @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

          – TT_
          Apr 19 '14 at 23:56














        • 10





          This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

          – Richard Chambers
          Apr 19 '14 at 13:22











        • @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

          – TT_
          Apr 19 '14 at 23:56








        10




        10





        This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

        – Richard Chambers
        Apr 19 '14 at 13:22





        This answer is somewhat confusing even though I have read over it a couple of times and took a look at the linked to question. I think that what it is saying is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body.

        – Richard Chambers
        Apr 19 '14 at 13:22













        @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

        – TT_
        Apr 19 '14 at 23:56





        @Richard Chambers It maybe confusing since English is not my first language, but you described precisely what I tried to say.

        – TT_
        Apr 19 '14 at 23:56











        19














        The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.



        Class2::Class2(string id) : Class1(id) {
        ....
        }


        Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.






        share|improve this answer






























          19














          The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.



          Class2::Class2(string id) : Class1(id) {
          ....
          }


          Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.






          share|improve this answer




























            19












            19








            19







            The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.



            Class2::Class2(string id) : Class1(id) {
            ....
            }


            Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.






            share|improve this answer















            The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.



            Class2::Class2(string id) : Class1(id) {
            ....
            }


            Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            answered Sep 23 '08 at 13:21


























            community wiki





            CR.
























                19














                If you have a constructor without arguments it will be called before the derived class constructor gets executed.



                If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:



                class base
                {
                public:
                base (int arg)
                {
                }
                };

                class derived : public base
                {
                public:
                derived () : base (number)
                {
                }
                };


                You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.






                share|improve this answer






























                  19














                  If you have a constructor without arguments it will be called before the derived class constructor gets executed.



                  If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:



                  class base
                  {
                  public:
                  base (int arg)
                  {
                  }
                  };

                  class derived : public base
                  {
                  public:
                  derived () : base (number)
                  {
                  }
                  };


                  You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.






                  share|improve this answer




























                    19












                    19








                    19







                    If you have a constructor without arguments it will be called before the derived class constructor gets executed.



                    If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:



                    class base
                    {
                    public:
                    base (int arg)
                    {
                    }
                    };

                    class derived : public base
                    {
                    public:
                    derived () : base (number)
                    {
                    }
                    };


                    You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.






                    share|improve this answer















                    If you have a constructor without arguments it will be called before the derived class constructor gets executed.



                    If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:



                    class base
                    {
                    public:
                    base (int arg)
                    {
                    }
                    };

                    class derived : public base
                    {
                    public:
                    derived () : base (number)
                    {
                    }
                    };


                    You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 26 '11 at 9:14









                    Mnementh

                    31.1k38130195




                    31.1k38130195










                    answered Sep 23 '08 at 13:19









                    Nils PipenbrinckNils Pipenbrinck

                    65.5k22133206




                    65.5k22133206























                        11














                        If you have default parameters in your base constructor the base class will be called automatically.



                        using namespace std;

                        class Base
                        {
                        public:
                        Base(int a=1) : _a(a) {}

                        protected:
                        int _a;
                        };

                        class Derived : public Base
                        {
                        public:
                        Derived() {}

                        void printit() { cout << _a << endl; }
                        };

                        int main()
                        {
                        Derived d;
                        d.printit();
                        return 0;
                        }


                        Output is: 1






                        share|improve this answer
























                        • This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                          – underscore_d
                          Feb 10 '16 at 23:21


















                        11














                        If you have default parameters in your base constructor the base class will be called automatically.



                        using namespace std;

                        class Base
                        {
                        public:
                        Base(int a=1) : _a(a) {}

                        protected:
                        int _a;
                        };

                        class Derived : public Base
                        {
                        public:
                        Derived() {}

                        void printit() { cout << _a << endl; }
                        };

                        int main()
                        {
                        Derived d;
                        d.printit();
                        return 0;
                        }


                        Output is: 1






                        share|improve this answer
























                        • This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                          – underscore_d
                          Feb 10 '16 at 23:21
















                        11












                        11








                        11







                        If you have default parameters in your base constructor the base class will be called automatically.



                        using namespace std;

                        class Base
                        {
                        public:
                        Base(int a=1) : _a(a) {}

                        protected:
                        int _a;
                        };

                        class Derived : public Base
                        {
                        public:
                        Derived() {}

                        void printit() { cout << _a << endl; }
                        };

                        int main()
                        {
                        Derived d;
                        d.printit();
                        return 0;
                        }


                        Output is: 1






                        share|improve this answer













                        If you have default parameters in your base constructor the base class will be called automatically.



                        using namespace std;

                        class Base
                        {
                        public:
                        Base(int a=1) : _a(a) {}

                        protected:
                        int _a;
                        };

                        class Derived : public Base
                        {
                        public:
                        Derived() {}

                        void printit() { cout << _a << endl; }
                        };

                        int main()
                        {
                        Derived d;
                        d.printit();
                        return 0;
                        }


                        Output is: 1







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 15 '14 at 18:49









                        edWedW

                        1,0551111




                        1,0551111













                        • This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                          – underscore_d
                          Feb 10 '16 at 23:21





















                        • This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                          – underscore_d
                          Feb 10 '16 at 23:21



















                        This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                        – underscore_d
                        Feb 10 '16 at 23:21







                        This is just because that particular declaration creates an implicit Base(), which has the same body as Base(int) but plus an implicit initialiser for : _a{1}. It's Base() that always gets called if no specific base constructor is chained in the init-list. And, as mentioned elsewhere, C++11's delegating constructors and brace-or-equal initialisation make default arguments rather less necessary (when they were already code-smell-esque in a lot of examples).

                        – underscore_d
                        Feb 10 '16 at 23:21













                        9














                        CDerived::CDerived()
                        : CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
                        {
                        //construct body
                        }





                        share|improve this answer




























                          9














                          CDerived::CDerived()
                          : CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
                          {
                          //construct body
                          }





                          share|improve this answer


























                            9












                            9








                            9







                            CDerived::CDerived()
                            : CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
                            {
                            //construct body
                            }





                            share|improve this answer













                            CDerived::CDerived()
                            : CBase(...), iCount(0) //this is the initialisation list. You can initialise member variables here too. (e.g. iCount := 0)
                            {
                            //construct body
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 23 '08 at 13:24









                            DyniteDynite

                            1,51732434




                            1,51732434























                                6














                                Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.






                                share|improve this answer





















                                • 2





                                  If nobody talked about it, where was it mentioned?

                                  – user207421
                                  Feb 12 '15 at 9:36






                                • 3





                                  @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                  – darth_coder
                                  Feb 12 '15 at 10:41
















                                6














                                Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.






                                share|improve this answer





















                                • 2





                                  If nobody talked about it, where was it mentioned?

                                  – user207421
                                  Feb 12 '15 at 9:36






                                • 3





                                  @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                  – darth_coder
                                  Feb 12 '15 at 10:41














                                6












                                6








                                6







                                Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.






                                share|improve this answer















                                Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 20 '16 at 2:26









                                User that is not a user

                                381719




                                381719










                                answered Mar 12 '14 at 10:46









                                darth_coderdarth_coder

                                6011535




                                6011535








                                • 2





                                  If nobody talked about it, where was it mentioned?

                                  – user207421
                                  Feb 12 '15 at 9:36






                                • 3





                                  @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                  – darth_coder
                                  Feb 12 '15 at 10:41














                                • 2





                                  If nobody talked about it, where was it mentioned?

                                  – user207421
                                  Feb 12 '15 at 9:36






                                • 3





                                  @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                  – darth_coder
                                  Feb 12 '15 at 10:41








                                2




                                2





                                If nobody talked about it, where was it mentioned?

                                – user207421
                                Feb 12 '15 at 9:36





                                If nobody talked about it, where was it mentioned?

                                – user207421
                                Feb 12 '15 at 9:36




                                3




                                3





                                @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                – darth_coder
                                Feb 12 '15 at 10:41





                                @EJP since the question is about calling rules , it is worth mentioning the sequence of calling in the answer

                                – darth_coder
                                Feb 12 '15 at 10:41


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f120876%2fwhat-are-the-rules-for-calling-the-superclass-constructor%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Tangent Lines Diagram Along Smooth Curve

                                Yusuf al-Mu'taman ibn Hud

                                Zucchini