Virtual function calls in constructors and destructors (C++)

Theory

#include <iostream>class A
{
public:
A() { std::cout << "A()\n"; };
virtual void foo() { std::cout << "A::foo()\n"; };
virtual void bar() { std::cout << "A::bar()\n"; };
};
class B : public A
{
public:
B() {
std::cout << "B()\n";
foo();
bar();
};
void bar() { std::cout << "B::bar()\n"; };
};
class C : public B
{
public:
C() { std::cout << "C()\n"; };
void foo() { std::cout << "C::foo()\n"; };
void bar() { std::cout << "C::bar()\n"; };
};
int main()
{
C x;
return 0;
}
A()
B()
A::foo()
B::bar()
C()
class Program
{
class Base
{
public Base()
{
Test();
}
protected virtual void Test()
{
Console.WriteLine("From base");
}
}
class Derived : Base
{
protected override void Test()
{
Console.WriteLine("From derived");
}
}
static void Main(string[] args)
{
var obj = new Derived();
}
}
From derived
class Base
{
public Base()
{
Test();
}
protected virtual void Test() { }
}
class Derived : Base
{
public String MyStr { get; set; }
public Derived(String myStr)
{
MyStr = myStr;
}
protected override void Test()
=> Console.WriteLine($"Length of {nameof(MyStr)}: {MyStr.Length}");
}

How this article appeared

class M {
public:
virtual int GetAge(){ return 0; }
};
class P : public M {
public:
virtual int GetAge() { return 1; }
P() { GetAge(); } // maybe warn
~P() { GetAge(); } // maybe warn
};

What if there’s no error here?

B() {
std::cout << "B()\n";
A::foo();
B::bar();
};

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store