I have a class derived from base class, and set constructors for each classes, but I keep getting error that I do not have any constructor for base class.
class Dog
{
protected:
string name;
int age;
public:
Dog(string dogsName, int dogsAge)
{
name = dogsName;
age = dogsAge;
}
virtual void Bark()
{
cout << "Woof Woof I am a dog" << endl;
}
class Huey: public Dog
{
public:
Huey()
{
name = "goodboy";
age = 13;
}
void Bark()
{
cout << "woof" << endl;
}
}
Here I get an error on Huey() and it says " no default constructor exists for 'Dog'". But I think I have created a constructor for class Dog. Can you please explain why this code is wrong?
When you specify any constructor of your own, the default constructor is not created anymore. However, you can just add it back.
class Dog
{
protected:
string name;
int age;
public:
Dog() = default;
Dog(string dogsName, int dogsAge)
{
name = dogsName;
age = dogsAge;
}
virtual void Bark()
{
cout << "Woof Woof I am a dog" << endl;
}
};
class Huey: public Dog
{
public:
Huey()
{
name = "goodboy";
age = 13;
}
void Bark()
{
cout << "woof" << endl;
}
};
EDIT: It seems like you want to call your custom Dog constructor from Huey. It is done like so
class Dog
{
protected:
string name;
int age;
public:
Dog(string dogsName, int dogsAge)
{
name = dogsName;
age = dogsAge;
}
virtual void Bark()
{
cout << "Woof Woof I am a dog" << endl;
}
};
class Huey: public Dog
{
public:
Huey() : Dog("goodboy", 13) {}
void Bark()
{
cout << "woof" << endl;
}
};
You need to create a constructor with no parameters and no implementation. As below:
public:
Dog() = default;
Two ways:
1) have a default constructor with no params.
2) call the existing constructor you have in Dog from Huey ( this is the right thing in your case since Huey is a Dog after all). Huey is currently calling the default constructor of Dog since this isn’t defined and explicitly called.
Related
I created two objects from derived classes (Dog and Cat), which I assigned to one common array, which is the Animal type. Now I want to check a single element of the array to see if it is a dog. If there is, I want it to execute a method from Dog class and bark.
#include <iostream>
using namespace std;
class Animal{
public:
Animal() {}
virtual ~Animal() {}
};
class Dog : public Animal{
public:
Dog() {}
virtual ~Dog() {}
void soundOf(){
cout << "Woof woof" << endl;
}
};
class Cat : public Animal{
public:
Cat() {}
virtual ~Cat() {}
void soundOf(){
cout << "Meoow" << endl;
}
};
int main() {
Animal animals[2];
Dog dog;
Cat cat;
animals[0] = dog;
animals[1] = cat;
Animal *ptr = animals+0;
Dog* dg = dynamic_cast<Dog*>(ptr);
if(dynamic_cast<Dog*>(ptr) != nullptr){
cout << "This is a dog" << endl;
dg->soundOf();
}else if(dynamic_cast<Cat*>(ptr) != nullptr){
cout << "This is a cat" << endl;
dg->soundOf();
}
return 0;
In "if", I also used the following method
if(Dog* dg = dynamic_cast<Dog*>(ptr))
But the effect was the same. It returned NULL every time.
When I wrote the same application in Java, it was enough to use "instanceof", but here I can't do it.
Others have commented as to why you are having this issue but have not really suggested a fix. You should get into the habit of using dynamically allocated objects and ensuring they behave nicely by using std::shared_ptr and std::vector.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Animal
{
public:
Animal() {}
virtual void soundOf() {}
virtual ~Animal() {}
};
class Dog : public Animal
{
public:
Dog() {}
virtual ~Dog() {}
void soundOf()
{
cout << "Woof woof" << endl;
}
};
class Cat : public Animal
{
public:
Cat() {}
virtual ~Cat() {}
void soundOf()
{
cout << "Meoow" << endl;
}
};
typedef std::shared_ptr<Animal> AnimalPtr;
int main()
{
std::vector<AnimalPtr> animals;
AnimalPtr dog = std::make_shared<Dog>();
AnimalPtr cat = std::make_shared<Cat>();
animals.push_back(dog);
animals.push_back(cat);
AnimalPtr ptr = animals[0];
if (dynamic_cast<Dog *>(ptr.get()) != nullptr)
{
cout << "This is a dog" << endl;
ptr->soundOf();
}
else if (dynamic_cast<Cat *>(ptr.get()) != nullptr)
{
cout << "This is a cat" << endl;
ptr->soundOf();
}
return 0;
}
this might seem long winded but will scale much better (and provides the functionality you want)
I have this UML Diagram and I have written the code below but I am struggling with an error message
However, while compiling and linking, I got an error
/tmp/cc9oQaPX.o: In function `main':
main.cpp:(.text+0x8c): undefined reference to `Fish::Fish(std::string)'
main.cpp:(.text+0xe5): undefined reference to `Cat::Cat(std::string)'
main.cpp:(.text+0x116): undefined reference to `Fish::Fish()'
main.cpp:(.text+0x158): undefined reference to `Cat::Cat()'
collect2: error: ld returned 1 exit status
#include <iostream>
using namespace std;
class Animal // define base class
{
protected:
int legs; // base class properties
public:
Animal(int legNumbers) // set values of leg
{
legNumbers = legs; // set values of leg
}
virtual void eat() = 0; // method of base class
virtual void walk() {}; // method of base class
};
class Pet // define the pet class
{
protected:
string name; // set properties of pet class
public:
virtual string getName(); // define method
virtual string setName(string name); // set name values
virtual void play() // define play method
{
cout << " garfield is playing now." << endl; // out values
}
};
class Spider :public Animal //child class inherit base class
{
public:
Spider() :Animal(8) // spider class inherit animal class
{
cout << "animals with " << legs << " legs is walking. " << endl;
}
virtual void eat() // define virtual method
{
cout << "spider is eating now. " << endl;
}
};
class Cat :public Pet, public Animal // cat inherit two classes
{
public:
Cat(string name); // set name method
Cat();
virtual void play() // define method
{
cout << name << " is playing now. " << endl;
}
virtual void eat(); // define method here
};
class Fish : public Pet, public Animal // fish inherit two method
{
public: // define public members
Fish(string name);
Fish();
virtual void play()
{
cout << name << " is playing now. " << endl;
}
virtual void eat(); // method here
void walk()
{
cout << " Fish cannot walk " << endl; // output the values
}
};
string Pet::getName() // get name value from parent class
{
return string();
}
string Pet::setName(string name)
{
return string();
}
int main(int argc, char* argv[]) // define main method
{
Fish* f = new Fish("Jaws");
Cat* c = new Cat("Tenkir");
Animal *a = new Fish();
Animal* e = new Spider();
Pet* p = new Cat();
f->play();
c->play();
e->eat();
e->walk();
a->walk();
p->play();
return 0;
}
This is right code.
Firstly, you didn't defined the constructors for Cat an Fish
But that wasn't the only problem.
Your functions walk, eat, play need to be override. And eat() has to have a block, becuase in the base class (Animal) is deleted, like eat() = 0;
#include <iostream>
using namespace std;
class Animal // define base class
{
protected:
int legs; // base class properties
public:
Animal(int legNumbers) // set values of leg
{
legs = legNumbers; // set values of leg
}
virtual ~Animal() {}
virtual void eat() = 0; // method of base class
virtual void walk() {}; // method of base class
};
class Pet // define the pet class
{
protected:
string name; // set properties of pet class
public:
virtual string getName(); // define method
virtual void setName(string name); // set name values
virtual void play() // define play method
{
cout << " garfield is playing now." << endl; // out values
}
};
string Pet::getName() // get name value from parent class
{
return this->name;
}
void Pet::setName(string name)
{
this->name = name;
}
class Spider :public Animal //child class inherit base class
{
public:
Spider() :Animal(8) // spider class inherit animal class
{
cout << "animals with " << legs << " legs is walking. " << endl;
}
virtual void eat() // define virtual method
{
cout << "spider is eating now. " << endl;
}
};
class Cat :public Pet, public Animal // cat inherit two classes
{
public:
Cat(string name)
:Animal(4)
{
this->setName(name);
} // set name method
Cat():Animal(4){}
~Cat() override {}
virtual void play() override // define method
{
cout << name << " is playing now. " << endl;
}
virtual void eat() override {} // define method here
};
class Fish : public Pet, public Animal // fish inherit two method
{
public: // define public members
Fish(string name)
:Animal(0)
{
this->setName(name);
}
Fish():Animal(0){}
~Fish() override {}
virtual void play() override
{
cout << name << " is playing now. " << endl;
}
virtual void eat() override {} // method here
void walk() override
{
cout << " Fish cannot walk " << endl; // output the values
}
};
int main(int argc, char* argv[]) // define main method
{
Fish* f = new Fish("Jaws");
Cat* c = new Cat("Tenkir");
Animal *a = new Fish();
Animal* e = new Spider();
Pet* p = new Cat();
f->play();
c->play();
e->eat();
e->walk();
a->walk();
p->play();
return 0;
}
I am trying to do something like this:
class Movement {
public:
virtual void move() = 0;
};
class Walk : public Movement {
public:
void move() { cout << "walking"; }
};
class Run : public Movement {
public:
void move() { cout << "run"; }
};
class Animal {
public:
virtual void print();
};
class Human : public Animal {
public:
void print() { cout << "Human"; }
};
class Lion : public Animal {
public:
void print() { cout << "Lion"; }
};
class Model {
Animal* animal;
Movement* movement;
public:
Model(Animal* animal = new Human(), Movement* movement = new Walk()) {
this->animal = animal;
this->movement = movement;
}
void print() {
cout << "This Model consist of one: ";
animal->print();
cout << ", which is: ";
movement->move();
}
};
int main() {
Model first = Model(), second = Model(new Lion(), new Run());
first.print();
cout << endl;
second.print();
return 0;
}
How do we set the default value for abstract class pointers & how to pass them as a parameter like that from main?
I would also prefer to be able to pass arguments from main like this only in a single line without needing to initialize before.
can anyone please help me with how do we such things in C++?
I have tried and searched a lot but no luck.
I am looking for a workaround to do something like this, in which we use an abstract classes as a parameter of other classes.
I know objects cannot be assigned to a pointer, I just don't know what to do there to fulfill my requirement, an abstract class as a parameter with a default value.
This is my latest attempt with exact code, but unfortunately with new, does anyone know how to get rid of new and achieve the desired outcome?
Note:
My actual code is quite complex, basically using an abstract class for polymorphism and pass those abstract classes as parameters to another class with default parameters, if there is ANY other way to do something similar I would really appreciate the help.
This is really a design question. In Modelclass design, you either need to decide about the object ownership, or defer the decision to the calling code. In the latter case, you cannot have default arguments (unless you want to have global constants Human and Walk, but I would not recommend it).
One way to have the default arguments is to decide that Model has exclusive ownership of Animal and Movement, and store unique_ptrs to them. Something like this:
class Model {
unique_ptr<Animal> animal;
unique_ptr<Movement> movement;
public:
Model(unique_ptr<Animal> animal = make_unique<Human>(), unique_ptr<Movement> movement = make_unique<Walk>()){
this->animal = std::move(animal);
this->movement = std::move(movement);
}
void print() {
cout << "This Model consist of one: ";
animal->print();
cout << ", which is: ";
movement->move();
}
};
int main() {
Model first/*no () here!*/, second(make_unique<Lion>(), make_unique<Run>());
first.print();
cout << endl;
second.print();
return 0;
}
I think I came up with the best solution for my situation.
#include <iostream>
#include <memory>
using namespace std;
class Movement {
public:
virtual void move() = 0;
virtual unique_ptr<Movement> movement() const = 0;
};
class Walk : public Movement {
public:
void move() { cout << "walking"; }
unique_ptr<Movement> movement() const { return make_unique<Walk>(); }
};
class Run : public Movement {
public:
void move() { cout << "run"; }
unique_ptr<Movement> movement() const { return make_unique<Run>(); }
};
class Animal {
public:
virtual void print() = 0;
virtual unique_ptr<Animal> animal() const = 0;
};
class Human : public Animal {
public:
void print() { cout << "Human"; }
unique_ptr<Animal> animal() const { return make_unique<Human>(); }
};
class Lion : public Animal {
public:
void print() { cout << "Lion"; }
unique_ptr<Animal> animal() const { return make_unique<Lion>(); }
};
class Model {
unique_ptr<Animal> animal;
unique_ptr<Movement> movement;
public:
Model(const Animal& animal = Human(), const Movement& movement = Walk()) {
this->animal = animal.animal();
this->movement = movement.movement();
}
void print() {
cout << "This Model consist of one: ";
animal->print();
cout << ", which is: ";
movement->move();
}
};
int main() {
Model first = Model(), second = Model(Lion(), Run());
first.print();
cout << endl;
second.print();
return 0;
}
Is your problem the compile error? There are multiple ways to address the compile error, but given that your question is about inheriting from abstract classes, I will focus on that.
First, as provided, your Animal class is not an abstract class. An abstract class cannot be instantiated because all its methods are pure virtual. In C++, pure virtual functions are designated by the virtual keyword prefix, and suffixed by = 0 in their definition. E.g.
...
virtual void print() = 0;
...
The following code is compilable by making your Animal class an abstract class:
#include <iostream>
using namespace std;
class Movement {
public:
virtual void move() = 0;
};
class Walk : public Movement {
public:
void move() { cout << "walking"; }
};
class Run : public Movement {
public:
void move() { cout << "run"; }
};
class Animal {
public:
virtual void print() = 0;
};
class Human : public Animal {
public:
void print() { cout << "Human"; }
};
class Lion : public Animal {
public:
void print() { cout << "Lion"; }
};
class Model {
Animal* animal;
Movement* movement;
public:
Model(Animal* animal = new Human(), Movement* movement = new Walk()) {
this->animal = animal;
this->movement = movement;
}
void print() {
cout << "This Model consist of one: ";
animal->print();
cout << ", which is: ";
movement->move();
}
};
int main() {
Model first = Model(),
second = Model(new Lion(), new Run());
first.print();
cout << endl;
second.print();
return 0;
}
Incidentally, your code can also be made compilable by providing an implementation for Animal::print(). The following code is also compilable, but Animal is not an abstract class because it provides an implementation for Animal::print() rather than suffixing it with = 0:
#include <iostream>
using namespace std;
class Movement {
public:
virtual void move() = 0;
};
class Walk : public Movement {
public:
void move() { cout << "walking"; }
};
class Run : public Movement {
public:
void move() { cout << "run"; }
};
class Animal {
public:
virtual void print() {};
};
class Human : public Animal {
public:
void print() { cout << "Human"; }
};
class Lion : public Animal {
public:
void print() { cout << "Lion"; }
};
class Model {
Animal* animal;
Movement* movement;
public:
Model(Animal* animal = new Human(), Movement* movement = new Walk()) {
this->animal = animal;
this->movement = movement;
}
void print() {
cout << "This Model consist of one: ";
animal->print();
cout << ", which is: ";
movement->move();
}
};
int main() {
Model first = Model(),
second = Model(new Lion(), new Run());
first.print();
cout << endl;
second.print();
return 0;
}
Otherwise, conceptually, what you're doing is fine and totally possible in C++: assigning a default value to a base class pointer that's in some function's argument list.
Important: As commenters have correctly pointed out, the pattern you have coded is dangerous: your interface is such that a user can optionally provide an Animal instance. The problem is: if the Model creator does, then it can be reasonably argued that he rightly owns the object. If he does not, then your constructor will create a new Animal instance, but neither does Model take ownership of the object, nor does it provide an interface by which the user can take ownership of the new Animal instance. This therefore creates a memory leak. Equally, the code hazard, is ambiguous ownership of the Animal instance used in the Model constructor.
I have just learnt about abstract class but I don't understand much. Is it possible to run abstract class functions and the inherited functions all at once?..
For example,
class Animals
{
public:
virtual void Display() = 0;
};
class Dog : public Animals
{
void Display()
{
cout << "This is Dog!" << endl;
};
class Cat : public Animals
{
void Display()
{
cout << "This is Cat!" << endl;
}
};
and I have another class called Zoo which will run the abstract function in class Animals
class Zoo : public Animals
{
Animals* animal;
animal->Display();
}
and the output I want is
This is Dog!
This is Cat!
When I run this, it has errors.. Is there any other ways to get this output? Thanks :)
First off, there's a syntax error:
class Animals
{
public:
virtual void Display() = 0;
};
class Dog : public Animals
{
void Display()
{
cout << "This is Dog!" << endl;
}
};
class Cat : public Animals
{
void Display()
{
cout << "This is Cat!" << endl;
}
};
Then if you want to create Dog and Cat instances you call new operators for these classes:
class Zoo : public Animals
{
void Display()
{
Animals* animal1;
animal1 = new Cat();
animal1->Display();
delete animal1;
Animals* animal2;
animal2 = new Dog();
animal2->Display();
delete animal2;
}
}
This should get your desired output.
animal->Display(); results in undefined behaviour because animal is not initialized, so first initialized it as
Cat my_cat;
Animals* animal = &my_cat;
animal->Display();
OR
Animals* animal = new Cat();
animal->Display();
....
delete animal;
Here is your Code, explanation is there in comments.
class Animals {
public:
virtual void Display() = 0;/*its a PVF , in every derived class it should be re-defined */
};
class Dog : public Animals {
void Display() {
cout << "This is Dog!" << endl;
};
};
class Cat : public Animals {
void Display() {
cout << "This is Cat!" << endl;
}
};
class Zoo : public Animals {
public :
void Display() {
#if 1
Dog my_dog;
Animals *animal = &my_dog; /** Display() of Animal class will be invoked bcz Display() is declared as virtual */
animal->Display();
#endif
#if 0
Animals* animal = new Cat(); /** Display() of Cat class eill be invoked */
animal->Display();
delete animal;
#endif
}
};
int main() {
Zoo my_zoo;
my_zoo.Display();
return 0;
}
I hope it helps you.
Is there a way to only call the base class and run the inherited classes too?
I think you want this:
#include <iostream>
#include <memory>
class Animals
{
public:
virtual void Display() = 0;
virtual ~Animals() = default;
};
class Dog : public Animals
{
void Display() override
{
std::cout << "This is Dog!" << std::endl;
}
};
class Cat : public Animals
{
void Display() override
{
std::cout << "This is Cat!" << std::endl;
}
};
class Goat : public Animals
{
void Display() override
{
std::cout << "This is Goat!" << std::endl;
}
};
int main()
{
Animals* animal = new Dog;
animal->Display();
delete animal; // delete at some point to avoid memory leak as Dog is allocated on the heap
Cat cat;
animal = &cat;
animal->Display(); // no delete needed, as Cat is allocated on the stack and will cleared when goes out of scope
std::unique_ptr<Animals> animal2 = std::make_unique<Goat>();
animal2->Display(); // no delete needed, Goat is allocated on the heap but will be cleared when goes out of scope
return 0;
}
https://ideone.com/yoVt4G
Threw std::unique_ptr in the mix for variety
I have the code:
#include <iostream>
#include <cstdlib>
using namespace std;
class Animal{
private:
int age;
public:
Animal() : age(1) {}
void toString(){
cout << "Age: " << age << endl;
}
};
class Cat : public Animal
{
public:
Cat() : age(5) {}
/*
void toString(){
cout << "Age: " << age << endl;
}*/
private:
int age;
};
int main(){
Cat tom;
tom.toString();
system("pause");
return 0;
}
But when I run the program, the age of the tom variable is 1, not 5. Does the toString can not read the age variable? If we open the /* */ the toString method in the Cat class, the age will be 5 !
(My english is not good very much. Thanks)
The problem is that Cat is writing to the age variable in Cat, while toString() reads the age variable in Animal, which, with Animal's constructor, is initialized to 1.
To solve this, you can provide another constructor for Animal which accepts an age parameter which is used to initialize Animal's age member variable.
class Animal{
private:
int age;
public:
Animal() : age(1) {}
Animal(int param_age) : age(param_age) {} // Initialize member variable age with parameter
void toString(){
cout << "Age: " << age << endl;
}
};
class Cat : public Animal
{
public:
Cat() : Animal(5) {} // Call Animal's constructor that set's the age
};
UPDATE: Another solution is to add a setter method in Animal class that sets its age. You can then call it in Cat's constructor to set the proper age.
class Animal{
private:
int age;
public:
Animal() : age(1) {}
void setAge(int age) { this->age = age; }
void toString(){
cout << "Age: " << age << endl;
}
};
class Cat : public Animal
{
public:
Cat() {
setAge(5);
}
};
Yet another alternative is to make Animal's age member protected
class Animal{
protected: // THIS
int age;
public:
Animal() : age(1) {}
void toString(){
cout << "Age: " << age << endl;
}
};
And remove Cat's age variable in the class definition. Despite its simplicity, this approach gives you more risk in encountering the "brittle base class" problem. Thus, I recommend the former solution as it is less prone to the said problem, and IMHO better sticks to the "write against interfaces, not implementations" principle.
The problem is that you are setting Cat::age in the Cat constructor, not the Animal::age used by Animal::toString.
Change the visibility of Animal::age to protected.
class Animal {
protected:
int age;
public:
Animal() : age(1) {}
void toString(){
cout << "Age: " << age << endl;
}
};
Don't redeclare a second age (which becomes Cat::age). Instead, change the value of age (Animal::age).
class Cat : public Animal {
public:
Cat() {
age = 5;
}
};
Try:
#include <iostream>
#include <cstdlib>
using namespace std;
class Animal{
private:
int age;
public:
Animal(int a = 1) // Pass in the age as a parameter.
: age(a) // Default to 1.
{}
// Prefer generic print function rather than toString()
friend std::ostream& operator<<(std::ostream& s, Animal const& a) {
return s << "Age: " << a.age << '\n'; // Prefer '\n' rather than endl
// Unless you really want to flush
// the stream (this is not usually
// the case).
}
};
class Cat : public Animal
{
public:
Cat()
: Animal(5) // Now you can call the base class constructor
{} // And get it to set 5
private:
// int age; // don't have a private copy here.
// use the one that is available in the base class.
// Prefer generic print function rather than toString()
friend std::ostream& operator<<(std::ostream& s, Cat const& a)
{
// Print Cat
// Then use the Animal priting function to print more information about the object.
return s << "A Cat: " << static_cast<Animal const&>(*a);
}
};
int main(){
Cat tom;
// tom.toString(); // Don't use a toString() method.
// overload operator<< to print to a stream.
// If you want to convert to a string the just print
// to a string stream.
std::cout << tom;
system("pause");
return 0;
}