Constructors and Virtual

Started by
3 comments, last by stylin 18 years, 6 months ago
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)
Advertisement
Which programming language are you asking about?
Sorry, C++
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(); }};
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;}
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid

This topic is closed to new replies.

Advertisement