This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Calling virtual functions inside constructors
class Base
{
virtual void method()
{ cout << "Run by the base."; };
public:
Base() { method(); };
};
class Derived: public Base
{
void method()
{ cout << "Run by the derived."; };
};
void main()
{
Derived();
}
Output:
Run by the base.
How can one have the derived method run instead, without making a derived constructor?
Calling virtual functions inside constructors
http://www.artima.com/cppsource/nevercall.html
You can't since the "derived" part of the object has not been constructed yet so calling a member function from it would be undefined behavior.
You can't do this without adding extra code.
A common way to achieve this is to use a private constructor and a create function that first calls the constructor (via new) and then a second finish_init method on the newly created object. This does prevent you from creating instances of the object on the stack though.
Related
This question already has answers here:
Calling virtual functions inside constructors
(15 answers)
Closed 7 years ago.
I'd like to do the following:
void do_stuff(Base* base_ptr) {
// here I need the overridden methods
base_ptr->init();
}
class Base {
Base() {
do_stuff(this);
}
virtual void init() {}
};
class Derived : public Base {
virtual void init() override {
// Derived specific init
}
}
But all I get are calls to Base::init(), is it even possible to do what I intend?
You are calling a virtual function from within the constructor!
Duplicated of -> Calling virtual functions inside constructors
This question already has answers here:
Calling virtual functions inside constructors
(15 answers)
Closed 7 years ago.
I have the following C++ code:
#include <iostream>
class Base {
public:
Base() { }
Base(const Base& other) { this->foo(); }
virtual ~Base() { }
virtual void foo() { std::cout << "Base::foo" << std::endl; }
};
class My : public Base {
public:
My() : Base() { }
My(const My& other) : Base(other) { }
virtual ~My() { }
void foo() { std::cout << "My::foo" << std::endl; }
};
int main(int argc, char** argv);
int main(int argc, char** argv) {
My* my = new My();
My* my2 = new My(*my);
}
Class My inherits from Base. The important thing is that Base has a virtual method foo which is overridden in My.
Polymorphism not kicking in
In the copy ctor of Base, called by My's copy ctor, I call foo. However I expect Base::Base(const Base&) to call My::foo, however when running the program I get:
Base::foo
Why is this happening? Should polymorphism have My::foo be called?
Dynamic dispatch is disabled during construction and destruction. This is by design. Inside a Base constructor, the My part of the object hasn't been constructed yet, so it makes no sense to call My's overrider, which might access uninitialized members of My or otherwise depend upon My's invariants that have not yet been established since My's constructor hasn't completed yet.
If this causes problems for you, you'll have to explain specifically what outcome you desire (post a new question) so workarounds can be suggested.
Why is this happening?
This is happening because the virtual table is not fully defined at that time. The virtual functions of derived classes are not set yet when base classes being constructed. They will be set in the virtual table when the derived classes are constructed.
Should polymorphism have My::foo be called?
No. The above explanation should suffice.
Virtual functions can be reliably called only inside the body of the constructor of the most derived class:
// This should work
My(const My& other) : Base(other) { this->foo(); }
You will find the answer in this. Virtual constructor is not available and with your code it would be that. So calling a virtual function from a constructor will not work in a way that you think.
This question already has answers here:
What is object slicing?
(18 answers)
Closed 8 years ago.
I checked this code, and i saw that by the end of the function func()
the destructor of base class have been called twice.
I dont understand why??
thank you..
class base {
public:
base(){cout << "ctor of base\n";}
~base(){cout << "d-ctor of base\n";}
};
class derived: public base
{
public:
derived(){cout << "ctor of derived\n";}
~derived(){cout << "d-ctor of derived\n";}
};
void func(base ob)
{
cout << "inside func\n";
}
void main()
{
derived ob;
func(ob);
system("pause");
}
Refactoring your base class like this:
class base {
public:
base(){cout << "ctor of base\n";}
base(const base&) {cout << "copy-ctor of base\n";}
~base(){cout << "d-ctor of base\n";}
};
would issue the following output:
ctor of base
ctor of derived
copy-ctor of base
inside func
d-ctor of base
d-ctor of derived
d-ctor of base
Showing pretty clearly your base variable inside func was copied and then destroyed.
base is passed by value to func.
This means a sliced copy of ob will be created.
This will be destroyed as well as ob itself. The destructor of ob (derived::~derived) will automatically call the base classes destructor.
Therefore the base destructor is called two times.
When you call the function you take the parameter by value. Therefore you create a local variable of type base in func.
When you return from func, the local variables are destroyed, so ob's descrutor (which has type base is called.
You have to pass polymorphic types via reference or pointer.
This is called the slicing problem. See this link for details.
This question already has answers here:
Why do we need virtual functions in C++?
(27 answers)
Closed 6 years ago.
In c++, the virtual function in base class can be overridden in derived class.
and a member function where the specific implementation will depend on the type of the object it is called upon, at run-time.
Since virtual function has to be implemented(except for pure virtual)
Can I use regular function in base class and redefine it in derived class?
if yes.
What's the point of using virtual function?
Thanks
You can redefine it but it won't work in a polymorphic way.
so if I have a
class base
{
int foo(){ return 3; }
};
class Der : public base
{
int foo() {return 5;}
};
and then have a function that takes a base
void dostuff(base &b)
{
b.foo(); // This will call base.foo and return 3 no matter what
}
and I call it like this
Der D;
dostuff(D);
Now if I change the base to
class base
{
virtual int foo(){ return 3; }
};
void dostuff(base &b)
{
b.foo(); // This will call the most derived version of foo
//which in this case will return 5
}
so the real answer is if you want to write common code that will call the correct function from the base it needs to be virtual.
Actually, Virtual function is base of object oriented language.
In java, all functions are virtual function.
But in c++, virtual function is slower than regular function.
So if there is no need to function override, you should use regular function instead of virtual function.
This question already has answers here:
C++ virtual function from constructor [duplicate]
(7 answers)
Closed 9 years ago.
I have this layout
class Base {
public:
virtual void Initialize() { // base Implementation }
Base() { Initialize(); }
};
class der_1 : public Base
{
public:
der_1() : Base() {}
virtual void Initialize() { // der_1 Implementation }
};
class der_2 : public Base
{
public:
der_2() : Base() {}
virtual void Initialize() { // der_2 Implementation }
};
Now, whenever I create a new object of class der_1 or der_2, I will end up calling the base implementation of Initialize(). Apparently, I can't call a virtual function while the object is being created.
As of now, I am calling the Initialize function after I create the object of type der_1 or der_2, which doesn't seem a correct practice to me as that will couple the Initialize function call to each time an object is created.
Can someone suggest me better alternatives?
During the constructor call, the object "is" still only an instance of the base class, so it does know about your overloaded Initialize() function.
There are some suggestions for dealing with the situation here:
C++ virtual function from constructor