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;
}

Recommended Answers

All 3 Replies

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

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.....

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;
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.