A
Al
Hi Folks,
I am reading C++ programming by Larry Ullman.
I am up to the section on Class Inheritance. The code is below. My
question is with the function setname, which is called twice by
cat.setName and dog.setName - as I read it name first is equal to
"Garfield" and then the second time it is called it is overwritten by
"Odie".
Then when name is used in cat.climb and dog.bark with std::cout << name
- by my reasoning its going to be "Odie"
Obviously this is not the case but I dont understand why???
Also why the function to set name = theName. Why not just cat.name =
"Garfield"
-Al
=================CODE==================
//pets.cpp
#include <iostream>
#include <string>
class Pet {
public:
void eat();
void sleep();
void setName(std::string theName);
std::string name;
};
class Cat : public Pet {
public:
void climb();
};
class Dog : public Pet {
public:
void bark();
};
void Pet::setName(std::string theName) {
name = theName;
}
void Pet::sleep() {
std::cout << name << "sleeps\n";
}
void Pet::eat() {
std::cout << name << "eats\n";
}
void Cat::climb() {
std::cout << name << "climbs a tree\n";
}
void Dog::bark() {
std::cout << name << "barks\n";
}
// Start Main Function
int main() {
Cat cat;
Dog dog;
cat.setName("Garfield");
dog.setName("Odie");
cat.sleep
cat.eat
cat.climb
dog.sleep
dog.eat
dog.bark
etc........
I am reading C++ programming by Larry Ullman.
I am up to the section on Class Inheritance. The code is below. My
question is with the function setname, which is called twice by
cat.setName and dog.setName - as I read it name first is equal to
"Garfield" and then the second time it is called it is overwritten by
"Odie".
Then when name is used in cat.climb and dog.bark with std::cout << name
- by my reasoning its going to be "Odie"
Obviously this is not the case but I dont understand why???
Also why the function to set name = theName. Why not just cat.name =
"Garfield"
From a confused newbie.
-Al
=================CODE==================
//pets.cpp
#include <iostream>
#include <string>
class Pet {
public:
void eat();
void sleep();
void setName(std::string theName);
std::string name;
};
class Cat : public Pet {
public:
void climb();
};
class Dog : public Pet {
public:
void bark();
};
void Pet::setName(std::string theName) {
name = theName;
}
void Pet::sleep() {
std::cout << name << "sleeps\n";
}
void Pet::eat() {
std::cout << name << "eats\n";
}
void Cat::climb() {
std::cout << name << "climbs a tree\n";
}
void Dog::bark() {
std::cout << name << "barks\n";
}
// Start Main Function
int main() {
Cat cat;
Dog dog;
cat.setName("Garfield");
dog.setName("Odie");
cat.sleep
cat.eat
cat.climb
dog.sleep
dog.eat
dog.bark
etc........