C++ examples for Class:Constructor
Passing Arguments to Base Constructors
#include <iostream> enum COLOR { RED, BLUE, WHITE, BLACK, EE, YELLOW }; class Pet //from w w w. j av a 2 s .c o m { public: // constructors Pet(); Pet(int age); ~Pet(); // accessors int getAge() const { return age; } void setAge(int newAge) { age = newAge; } int getWeight() const { return weight; } void setWeight(int newWeight) { weight = newWeight; } // other member functions void speak() const { std::cout << "Pet sound!\n"; } void sleep() const { std::cout << "Shhh. I'm sleeping.\n"; } protected: int age; int weight; }; class Dog : public Pet { public: // constructors Dog(); Dog(int age); Dog(int age, int weight); Dog(int age, COLOR color); Dog(int age, int weight, COLOR color); ~Dog(); // accessors COLOR getBreed() const { return color; } void setBreed(COLOR newBreed) { color = newBreed; } // other member functions void wagTail() { std::cout << "Tail wagging ...\n"; } void begForFood() { std::cout << "Begging for food ...\n"; } private: COLOR color; }; Pet::Pet(): age(1), weight(5) { std::cout << "Pet constructor ...\n"; } Pet::Pet(int age): age(age), weight(5) { std::cout << "Pet(int) constructor ...\n"; } Pet::~Pet() { std::cout << "Pet destructor ...\n"; } Dog::Dog(): Pet(), color(RED) { std::cout << "Dog constructor ...\n"; } Dog::Dog(int age): Pet(age), color(RED) { std::cout << "Dog(int) constructor ...\n"; } Dog::Dog(int age, int newWeight): Pet(age), color(RED) { weight = newWeight; std::cout << "Dog(int, int) constructor ...\n"; } Dog::Dog(int age, int newWeight, COLOR color): Pet(age), color(color) { weight = newWeight; std::cout << "Dog(int, int, COLOR) constructor ...\n"; } Dog::Dog(int age, COLOR newBreed): Pet(age), color(newBreed) { std::cout << "Dog(int, COLOR) constructor ...\n"; } Dog::~Dog() { std::cout << "Dog destructor ...\n"; } int main() { Dog fido; Dog rover(5); Dog buster(6, 8); Dog yorkie (3, RED); Dog dobbie (4, 20, EE); fido.speak(); rover.wagTail(); std::cout << "Yorkie is " << yorkie.getAge() << " years old\n"; std::cout << "Dobbie weighs " << dobbie.getWeight() << " pounds\n"; return 0; }