Skip to content

Instantly share code, notes, and snippets.

@junfenglx
Created February 9, 2015 13:23
Show Gist options
  • Save junfenglx/3900075dd3311e875e11 to your computer and use it in GitHub Desktop.
Save junfenglx/3900075dd3311e875e11 to your computer and use it in GitHub Desktop.
In class constructor and destructor call virtual functions
#include <iostream>
class Base {
public:
Base() {
std::cout << "Base Constructor" << std::endl;
ctor();
}
virtual ~Base() {
std::cout << "Base Destructor" << std::endl;
dtor();
}
virtual void ctor() {
std::cout << "in Base::ctor" << std::endl;
}
virtual void dtor() {
std::cout << "in Base::dtor" << std::endl;
}
};
class Derived: public Base {
public:
Derived() {
std::cout << "Derived Constructor" << std::endl;
ctor();
}
~Derived() {
std::cout << "Derived Destructor" << std::endl;
dtor();
}
virtual void ctor() {
std::cout << "in Derived::ctor" << std::endl;
}
virtual void dtor() {
std::cout << "in Derived::dtor" << std::endl;
}
};
int main() {
Base *pb = new Derived();
delete pb;
}
@junfenglx
Copy link
Author

g++ -std=c++14 -g -Wall -Wextra -pedantic -pthread -pedantic-errors test_vitual_func.cc
./a.out
Base Constructor
in Base::ctor
Derived Constructor
in Derived::ctor
Derived Destructor
in Derived::dtor
Base Destructor
in Base::dtor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment