Question: using c++ language divide program to main.cpp,animal.h,animal.cpp need use g++ -o count animal.cpp main.cpp in terminal to compile Part 1 - Simple Classes and

using c++ language

divide program to main.cpp,animal.h,animal.cpp

need use "g++ -o count animal.cpp main.cpp "in terminal to compile

Part 1 - Simple Classes and Class Variables

1-1

Define and implement a class named animal that has the following public constructors and behaviours:

animal(string aSpecies) ; // animals are allocated a unique ID on creation, // the first animal has ID 1, the second animal is 2 and so on void set_name(string aName); // change the animal's name
string get_species(); string get_name(); int get_ID(); // the animal's unique ID

This should be straight forward except for the ID. How do we keep track of what ID number we are up to? The solution to this problem is to declare a class variable as we saw in the Panda example. A class variable as its name implies is a variable that belongs to the class itself, not object instances. It is declared in the class declaration (just like other state variable) but is identified as a class variable by the keyword static. There is only one copy of this variable no matter how many object instances are created.

Class variables are declared in the .h file but they cannot be initialised in a constructor and must be initialised in the .cpp file. For example, if the animal class has a class variable that is named currentID and that must be initialised to 0, the animal.h file must contain:

static int currentID ; // the next id number to give out

and the animal.cpp file must contain (outside of any of the method implementations):

int animal::currentID = 0 ;

You can access the currentID variable when you are creating objects of class animal. Think carefully about this use. currentID should be 1 when you create your first animal, 2 when you create your second animal, and so on. What will you need to do to currentID whenever you create an animal? Each animal must have their own unique ID. Do they need their own state variable to hold this unique ID or can they use currentID?

Your main program should create two animal objects, an "Elephant" and a "Cheetah", then display their details. Your main program should demonstrate that the name can be changed.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!