0

here is my codes, i plan to output the name and the weight.
but no matter i try many time it still give me an output only
output should be this->
Name = Meow
Weight = 10.5
whereas what am I getting is
Weight = 10.5, why?
thx

#include <iostream>
using namespace std;

class Animal {
	string name;
public:
	Animal (string name)
		: name(name) {}
	void print() const {
		cout << "Name = " << name << endl; 
	}
};

class Cat : public Animal{
	double weight;
 public:
	Cat(string name, double weight)
		: Animal(name), weight(weight) {this-> weight = weight;} 
	void print() const {
		cout << "Weight = " << weight << endl;
	}
};

int main() {
	Cat c("Meow", 10.5);
	c.print();
	
	return 0;
}

Edited by Nick Evan: Added code-tags

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by vijayan121
0

It is because you are calling print() with Cat class object and c.print(); only calls print method of Cat class not Animal class.

0

It is because you are calling print() with Cat class object and c.print(); only calls print method of Cat class not Animal class.

but is there anyway for me to reuse the method from the Animal class and call it out?
this is inheritance right? so we will not going to rewrite the same thing in other difference class...but if i disable the following line
// cout << "Weight = " << weight << endl;
it will call the method from the Animal class.....

0
class Cat : public Animal{
	double weight;
 public:
	Cat(string name, double weight)
		: Animal(name), weight(weight) {this-> weight = weight;} 
	void print() const {
                Animal::print() ; // *** added *** 
		cout << "Weight = " << weight << endl;
	}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.