Getting started
Literals
Basic type keywords
Operator precedence
Floating point arithmetic
Bit operators
Bit manipulation
Bit fields
Arrays
Flow control
const keyword
Loops
mutable keyword
friend keyword
keywords
Variable declaration keywords
auto keyword
Pointers
Type keywords (class, enum, struct, union)
Classes / structs
std::string
Enumeration
std::atomic<T>
std::vector
std::array
std::pair
std::map
std::unordered_map
std::set and std::multiset
std::any
std::variant
std::optional
std::integer_sequence
std::function
std::forward_list
std::iomanip
Iterators
Basic I/O
File I/O
Streams
Stream manipulators
Metaprogramming
Returning multiple values from a function
References
Polymorphism
Value and reference semantics
Function call by value vs. by reference
Copying vs assignment
Pointers to class / struct members
The this pointer
Smart pointers
Unions
Templates
Namespaces
Function overloading
Operator overloading
Lambdas
Threading
Value categories
Preprocessor
SFINAE
Rule of three, five and zero
RAII
Exceptions
Implementation-defined behavior
Special member functions
Random numbers
Sorting
Regular expressions
Perfect forwarding
Virtual member functions
Syntax
Remarks
Using override with virtual in C++ 11
Virtual vs non-virtual member functions
Final virtual functions
Behaviour of virtual functions in constructors and destructors
Pure virtual functions
Undefined behavior
Overload resolution
Move semantics
Pimpl idiom
Copy elision
Fold expressions
Unnamed types
Singleton
ISO C++ Standard
User-defined literals
Type erasure
Memory management
Explicit type conversions
RTTI
Standard library algorithms
Expression templates
Scopes
Atomic types
static assert
constexpr
Date and time with std::chrono
Trailing return type
Function template overloading
Common compile linker errors
Design patterns
Optimizations
Compiling and building
Type traits
One definition rule
Unspecified behavio
Argument dependent name lookup
Attributes
Internationalization
Profiling
Return type covariance
Non-static member functions
Recursion
Callable objects
Constant class member functions
C++ vs. C++ 11 vs C++ 17
Inline functions
Client server examples
Header files
Const correctness
Refactoring techniques
Parameter packs
Iteration
type deduction
C++ 11 memory model
Build systems
Concurrency with OpenMP
Type inference
Resource management
Storage class specifiers
Alignment
Inline variables
Linkage specifications
Curiusly recurring template pattern
Using declaration
Typedef and type aliases
Layout of object types
C incompatibilities
Optimization
Semaphore
Thread synchronization
Debugging
Futures and promises
More undefined behaviors
Mutexes
Recursive mutex
Unit testing
decltype
Digit separators
C++ Containers
Arithmetic meta-programming
Contributors

Behaviour of virtual functions in constructors and destructors

suggest change

The behaviour of virtual functions in constructors and destructors is often confusing when first encountered.

#include <iostream>
using namespace std;

class base { 
public:
    base() { f("base constructor"); }
    ~base() { f("base destructor"); }

    virtual const char* v() { return "base::v()"; }

    void f(const char* caller) { 
        cout << "When called from " << caller << ", "  << v() << " gets called.\n"; 
    }        
};

class derived : public base {
public:
    derived() { f("derived constructor"); }
    ~derived() { f("derived destructor"); }

    const char* v() override { return "derived::v()"; }

};

int main() {
     derived d;
}

Output:

When called from base constructor, base::v() gets called.

When called from derived constructor, derived::v() gets called.

When called from derived destructor, derived::v() gets called.

When called from base destructor, base::v() gets called.

The reasoning behind this is that the derived class may define additional members which are not yet initialized (in the constructor case) or already destroyed (in the destructor case), and calling its member functions would be unsafe. Therefore during construction and destruction of C++ objects, the dynamic type of *this is considered to be the constructor’s or destructor’s class and not a more-derived class.

Example:

#include <iostream>
#include <memory>

using namespace std;
class base {
public:
    base()
    {
        std::cout << "foo is " << foo() << std::endl;
    }
    virtual int foo() { return 42; }
};

class derived : public base {
    unique_ptr<int> ptr_;
public:
    derived(int i) : ptr_(new int(i*i)) { }
    // The following cannot be called before derived::derived due to how C++ behaves, 
    // if it was possible... Kaboom!
    int foo() override   { return *ptr_; } 
};

int main() {
    derived d(4);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents
12 Loops
52 Unions
61 SFINAE
63 RAII
85 RTTI
88 Scopes
140 Mutexes