• Advertisement

Archived

This topic is now archived and is closed to further replies.

C++ equivalent of super(...)

This topic is 5504 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there anything in C++ that one can use to call the constructor of a parent class from within the constructor of a child class? This is similar to Java''s super(...), if anyone is familiar with that.

Share this post


Link to post
Share on other sites
Advertisement
Yes, you can do the following:

Derived::Derived()
{

Base::Base();

}


In this case Derived inherits from Base.

Share this post


Link to post
Share on other sites

  

class Baseclass
{
public:
Baseclass();
};

class Derived : public Baseclass
{
public:
Derived();
};

// either do this:

Derived::Derived() : Baseclass()
{

};

// or do this:

Derived::Derived()
{
::Baseclass();

// or even

Baseclass::Baseclass();

// or even this works i think:


Baseclass();
};




I have spoken.

Share this post


Link to post
Share on other sites
The constructor of the base class will be called before the constroctor of the derived class. You don''t need to do this yourself.

My Site

Share this post


Link to post
Share on other sites
...unless you want to use something else than the default constructor.

Share this post


Link to post
Share on other sites
Yeah, my problem was that I wanted to extend ifstream and ofstream so that the write and read commands could accept any type of data, rather than just char*. So, being able to call the non-default constructor is rather important... It''s working well now though, so thanks!

Share this post


Link to post
Share on other sites

  • Advertisement