Ask Your Question
3

What is the method for invoking a virtual method of a derived class from the constructor of the base class?

asked 2023-06-06 00:41:59 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-06 01:06:02 +0000

huitzilopochtli gravatar image

It is generally not recommended to invoke a virtual method of a derived class from the constructor of the base class because the object may not be fully initialized yet. However, if it is necessary to do so, the following approach can be used:

  1. Declare the virtual method in the base class and implement it in the derived class.
  2. Call the virtual method in the constructor of the base class, using the syntax this->virtual_method() or Base::virtual_method().
  3. Ensure that any code in the virtual method does not rely on uninitialized members or behavior.

Example:

class Base {
public:
    Base() {
        this->initialize(); // Calls virtual method defined in derived class
    }

    virtual void initialize() {
         // This method will be overridden in the derived class
    }
};

class Derived : public Base {
public:
    Derived() {}

    void initialize() override {
         // Code to initialize the derived class
    }
};
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 00:41:59 +0000

Seen: 2 times

Last updated: Jun 06 '23