Jump to content
  • Advertisement
Sign in to follow this  
Axiverse

Constructors and Virtual

This topic is 4654 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!