When I call a copy constructor for class B with values (string lan, const B& kop) in the initialization list of this constructor, I use B(kop) which is an undefined copy constructor.
As I understand it, the compiler then creates such a constructor itself, and miraculously it manages to copy the lan and licz fields of the base class and, of course, its own tf field.
However, in my opinion, it should not be possible because these two fields are private in the base class and public setters are needed in the base class, e.g. for licz I have not defined one. Does the compiler create such a setter itself?
Nevertheless, the program executes correctly.
Please explain how this happens from a technical perspective, and how the compiler deals with it.
abc.h:
#ifndef ABC_H_INCLUDED #define ABC_H_INCLUDED #include <iostream> #include <string> #include <iomanip> using namespace std; class A { private: string lan; int licz; public: A(string lan, int licz) : lan(lan), licz(licz) {} virtual void drukuj() const { cout<<lan<<" ; "<<licz<<endl; } string getLen() const { return lan; } int getLicz() const { return licz; } void setString(string lan) { this->lan=lan; } }; class B : public A { private: bool tf; public: B(string lan, int licz, bool tf) : A(lan,licz), tf(tf){} B(string lan, const B& kop) : B(kop) { A::setString(lan); } void drukuj() const override { cout<<boolalpha<<A::getLen()<<" ; "<<A::getLicz()<<" ; "<<tf<<endl; } }; #endif // ABC_H_INCLUDED main.cpp:
#include "abc.h" int main() { A a("obiekt klasy A",1); B b("obiekt klasy B", 2, true); B c("kopia obiektu b", b); a.drukuj();//drukuje wszystkie składowe obiektu a b.drukuj(); c.drukuj(); return 0; }