'derived class can be called with base copy constructor
in the following code example i have two class, one is derived from the other, they only differ in the output message ("base" vs "derived")
from the main i call both of them, then i use the copy constructor from Base with Derived as a parameter, and it works. even though i don't have a prototype function for such a call :
#include <iostream>
class Base {
public:
Base() {
std::cout << "base default constructor\n";}
Base(int i) {
std::cout << "base parameters constructor\n";}
Base(Base const & src) {
std::cout << "base copy constructor\n"; *this = src;}
Base & operator=(Base const & rhs) {
std::cout << "base assignation operator\n"; return *this;}
~Base() {
std::cout << "base default destructor\n";}
};
class Derived : public Base {
public:
Derived() {
std::cout << "derived default constructor\n";}
Derived(int i) {
std::cout << "derived parameters constructor\n";}
Derived(Derived const & src) {
std::cout << "derived copy constructor\n"; *this = src;}
Derived & operator=(Derived const & rhs) {
std::cout << "derived assignation operator\n"; return *this;}
~Derived() {
std::cout << "derived default destructor\n";}
};
int main () {
Base base1(1); std::cout << "\n";
Derived derived1(1); std::cout << "\n";
Base base2(derived1); std::cout << "\n";
return 0;
}
and the output :
base parameters constructor
base default constructor
derived parameters constructor
base copy constructor
base assignation operator
base default destructor
derived default destructor
base default destructor
base default destructor
i was expecting an error like (inversion of output for the call of Derived derived2(base1);) :
main.cpp:36:24: error: no matching function for call to ‘Base::Base(Derived&)’
36 | Base base2(derived1);
| ^
main.cpp:23:2: note: candidate: ‘Base::Base(const Base&)’
23 | Base(Base const & src) {
| ^~~~
why does it works ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
