I am a newbie in C++. I wrote this code to understand the difference between public, protected and private. The problem is, when I create an object of Hund4, I get this error:
use of deleted function
This error is in the last line.
Can you please help me to solve this problem?
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
class Tier
{
public:
void wieMachtDasTier()
{
cout << "Hello\n";
}
protected:
void foo()
{
cout << "foo\n";
}
private:
void baz()
{
cout << "baz\n";
}
};
class Hund: public Tier
{
private:
string name;
public:
Hund(string newname):name(newname){}
string getname()
{
return this->name;
}
void test()
{
foo();
}
};
class Hund2: protected Tier
{
public:
void test()
{
foo();
}
};
class Hund3: private Tier
{
public:
void test()
{
foo();
}
};
class Hund4 : public Hund
{
};
int main()
{
Hund ace("ace");
ace.wieMachtDasTier();
Tier Haustier;
ace.test();
Hund2 ace2;
ace2.test();
Hund3 ace3;
ace3.test();
Hund4 ace4;
return 0;
}
>Solution :
Tier has no user-declared constructors, and std::string is default-constructable, so Tier has a compiler-generated default constructor.
Hund2 and Hund3 derive from Tier, have no user-declared constructors, and do not have any non-default-constructable data members, so they have compiler-generated default constructors as well.
Hund, on the other hand, has a user-declared constructor, so it does not have a compiler-generated default constructor.
Hund4 has no user-declared constructors, but Hund is not default-constructable, so Hund4 does not have a compiler-generated default constructor.
So, if you want Hund4 to be default-constructable, you need to either:
-
make
Hunddefault-constructable, eg:class Hund: public Tier { private: string name; public: Hund() {} Hund(string newname) : name(newname) {} // or: // Hund(string newname = "") : name(newname) {} ... }; -
give
Hund4its own user-declared default constructor, which callsHund‘s non-default constructor, eg:class Hund4 : public Hund { public: Hund4() : Hund("") { } // or: // Hund4(string newname = "") : Hund(newname) { } };