can't take member of base class from derived class. C++ - c++

I have 2 classes. Base - Animal and derived MyDog. I want to change the ageOfAnimal from the setAge method and then display changed value from derived class - MyDog
code:
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
int ageOfAnimal = 0;
int setAge(int age) {
ageOfAnimal = age;
return ageOfAnimal;
}
};
class MyDog: public Animal
{
public:
void getInfo() {
cout << ageOfAnimal;
}
};
int main()
{
Animal *animal = new Animal;
animal->setAge(20);
MyDog myDog;
myDog.getInfo();
return 0;
}
Output: 0
Why can't I get 20? Is this even posible?
UPDATE
Thanks for answers but what i want is to change the state of ageOfAnimal property from different objects
class Animal
{
public:
int ageOfAnimal = 0;
int setAge(int age) {
ageOfAnimal += age;
return ageOfAnimal;
}
}
class MyCat: public Animal
{
public:
void getInfo() {
cout << ageOfAnimal;
}
}
class MyDog: public Animal
{
public:
void getInfo() {
cout << endl << ageOfAnimal;
}
}
int main() {
myDog dog;
dog.getInfo();
MyCat cat;
cat.getInfo();
}
output:
20
20
but what i want to see it's 20 21. How to do this?

In the usage code there are two different objects: Animal * animal and MyDog myDog. Both objects have their own instances of ageOfAnimal: changing it in one object does not modify the second object (which is the expected behavior).
1. As MyDog is derived from Animal one could simply:
MyDog myDog;
myDog.setAge(20);
myDog.getInfo();
2. If you want ageOfAnimal to be global for all instances of Animal you should make it a static member.
UPDATE
To reflect the updated question: one can put getInfo into Animal class. Default age for cats and dogs can be then specified in the constructors.
Even better way would be to specify age in Animal ctor and use constructor initializer lists for MyDog and MyAnimal ctors.
class Animal
{
public:
int ageOfAnimal = 0;
int setAge(int age)
{
ageOfAnimal += age;
return ageOfAnimal;
}
void getInfo()
{
cout << endl << ageOfAnimal;
}
};
class MyCat : public Animal
{
public:
MyCat()
{
setAge(40);
}
};
class MyDog : public Animal
{
public:
MyDog()
{
setAge(20);
}
};
int main()
{
MyDog dog;
dog.getInfo();
MyCat cat;
cat.getInfo();
}
Output:
20
40
Or if you want age to be shared between all objects, make it a static member as suggested earlier:
class Animal
{
public:
static int ageOfAnimal;
int setAge(int age)
{
ageOfAnimal += age;
return ageOfAnimal;
}
void getInfo()
{
cout << ageOfAnimal;
}
};
// Initialize age
int Animal::ageOfAnimal = 0;

Related

Polymorphysm Derived and Base class with :: Operator

The following programm creates a simple base class(Animal) and some derived classes(Frog,Cat).
The question occurs when typing Cat:: or Animal:: (See Code and you'llunderstand the question better)
#include <iostream>
using namespace std;
class Animal
{
protected:
int ID=4;
public:
void getID();
};
void Animal::getID()
{
cout << Animal::ID << endl;
}
class Frog:public Animal
{
public:
Frog();
};
Frog::Frog()
{
Animal::ID = 1;
}
class Cat:public Animal
{
public:
Cat();
};
Cat::Cat()
{
Cat::ID = 500;
}
int main()
{
Frog frog;
Cat cat;
cat.getID();
frog.getID();
}
/*
500
1
is printed to the screen
Question:
in line 26 whether I type Animal::ID=1;or Frog::ID=1;
I get the same result.
So in the derived class Frog, Animal:: and Frog:: are the same thing??
When I type Animal:: the programm understands Frog:: ??
(Same goes with Cat obviously)
*/
PS: Is there a way to cout the base(Animal) Class ID from a derived class(ex. Frog)??
(ex. frog.getID().SomeOtherFunction and the ID 4(Of the animal class is printed))

C++ passing data from object of class A to object of derived class B

For the sample code below, I'm trying to pass (or attribute, if that suits you better) the data from object of class A to the object of derived class B. What I don't understand so far, is how do I transfer the data from the parent class object, to the derived class object.
The "code" below expresses how I've tried to do that.
class Foo {
protected:
string Name, Surname;
public:
void readData()
{
cin >> Name >> Surname >> ;
}
}
class Bar : public Foo {
public:
Bar(Foo a)
{
Name = Name;
Surname = Surname;
}
void printData()
{
//code
}
}
int
main()
{
Foo a;
a.readData();
Bar b(a);
b.printData()
}
Minimal changes to make your code compile is using Foos copy constructor and simply access the inherited members in Bar::printData:
#include <string>
#include <iostream>
class Foo{
protected:
std::string Name, Surname;
public:
void readData()
{
std::cin >> Name >> Surname;
}
};
class Bar : public Foo
{
public:
Bar (const Foo& a) : Foo(a) { }
void printData()
{
std::cout << Name << " " << Surname;
}
};
int main()
{
Foo a;
a.readData();
Bar b(a);
b.printData();
}

Default value for abstract class pointer parameter

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.

Error: no default constructor exists for class

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.

accessing protected inheritance

I have to inherit protected members of base class and keep as protected in derived also.
For-example: base class has set() and get() protected and they should be protected in derived also.
The problem is as they are protected in derived so how to access.
Actually I was trying to do this:
#include<iostream>
#include<string>
using namespace std;
class Animal
{
protected:
string name;
void setName(string a){ name = a; }
void getName(){ cout << name << endl; }
};
class Cat :public Animal
{
public:
Cat(string dc){
setName(dc);
}
void printName(){ getName(); }
};
class Dog :public Animal
{
public:
Dog(string dc2){
setName(dc2);
}
void printName(){ getName(); }
};
int main()
{
Cat c("Mano");
c.printName();
Dog d("Tommy");
d.printName();
system("pause");
return 0;
}