Sign in to follow this  
Axiverse

Constructors and Virtual

Recommended Posts

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

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