Monday, 19 November 2018

c++ - What are the rules for calling the superclass constructor?




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).


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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...