Sign in to follow this  

Constructors and Virtual

This topic is 4470 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

Can you call another constructor in one constructor? And How do you call a function of a parent class in the child class (equivalent to the MyBase keyword in vb.net)

Share this post


Link to post
Share on other sites
You can't call a differnt constructor of the same class in a constructor, but you can call the constructor of a base class. To call a base class's version of a function, you prefix a call with the base class's name + :: ex:

class MyBase {
public:
MyBase(int i) { /* stuff */ }

void my_function(void) { std::cout << "Base" << std::endl; }
};

class MyClass : public MyBase {
public:
MyClass() : MyBase(42) { /* stuff */ }

void my_function(void) { MyBase::my_function(); }
};

Share this post


Link to post
Share on other sites
And it works the same for virtual functions as well. You need to tell the compiler which veresion of the function you want by qualifying it (or not):

#include <iostream>

class base {
public:
virtual void vfunction() { std::cout << "base::vfunction()" << std::endl; }
};

class derived : public base {
public:
void vfunction() { std::cout << "derived::vfunction()" << std::endl; }
};

int main() {

base * pb = new derived; // initialize a base pointer to derived

pb->vfunction(); // calls derived::vfunction()
pb->base::vfunction(); // calls base::vfunction()

delete pb;

return 0;
}

Share this post


Link to post
Share on other sites

This topic is 4470 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this