Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overridden function from a base class?

My question will probably be best explained by an example.

For example, I have 2 classes: A base class and a derived class:

class baseClass
{
public:
    baseClass()
    {
        foo();
    }
    virtual bool foo() { printf("baseClass"); return false;}

};

class derivedClass : public baseClass
{
public:
    bool foo()
    {
        printf("derivedClass");
        return true;
    }

};

When I create an instance of derivedClass, the constructor in baseClass will be called, and foo() will be called from it's constructor. The problem is, the baseClass' constructor is calling its own foo() and no the overridden foo() that the derived class has overridden. Is there anyway to make the baseClass call the overridden function, not it's own definition of the function?

like image 397
Brad Avatar asked Nov 01 '10 21:11

Brad


People also ask

How do you access the overridden method of base class from the derived?

6. How to access the overridden method of base class from the derived class? Explanation: Scope resolution operator :: can be used to access the base class method even if overridden. To access those, first base class name should be written followed by the scope resolution operator and then the method name.

How do you call a derived function from base class?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

How do you access an overridden method from a derived class in C#?

To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword with derived class method.


1 Answers

You should not call a virtual method from a constructor because the object has not yet been fully constructed. Essentially, the derived class doesn't exist yet, so its methods cannot be called.

like image 178
Sydius Avatar answered Sep 30 '22 10:09

Sydius