I have been reading "Sams Teach Yourself C++ in 24 Hours". This is the code that has confused me:

#include <iostream> 

class Cat 
{
public: 
int GetAge(); 
void SetAge (int age);
void Meow(); 

private: 
int itsAge; 
};

int Cat::GetAge()
{
return itsAge;
}

void Cat::SetAge(int age)
{
itsAge = age;
}

void Cat::Meow()
{
std::cout << "Meow.\n";
}

int main()
{
Cat Frisky;
Frisky.SetAge(5);
Frisky.Meow();
std::cout << "Frisky is a cat who is";
std::cout << Frisky.GetAge() << " years old.\n";
Frisky.Meow();
return 0;
}

Everything i understands except this:

int Cat::GetAge()
{
return itsAge;
}

void Cat::SetAge(int age)
{
itsAge = age;
}

void Cat::Meow()
{
std::cout << "Meow.\n";
}

if anyone can explain why the author did this it would be greatly appreciated ;)

Recommended Answers

All 9 Replies

He wanted to show you how to use private elements in classes. You can't call private methods and variables directly!

This is a classic example of Encapsulation in C++.
You hide data and code by using access modifiers private and protected.
If you don’t explicitly write an access modifier, by default it is private for class and public for structure in C++.

You should use inline functions when declaring them in the class itself, you can do this by simply typing void SetAge (int age) [b] { return itsAge = age } [/b] so you wouldnt need to use the scope operator later with the int Cat:: in front of the function. You do not need to define which class the function is in, because it is locally declared when the class is set up.

ok thx everybody now i got it :)

Oh yea and Merry Christmas ;)

You should use inline functions when declaring them in the class itself, you can do this by simply typing void SetAge (int age) [b] { return itsAge = age } [/b] so you wouldnt need to use the scope operator later with the int Cat:: in front of the function. You do not need to define which class the function is in, because it is locally declared when the class is set up.

Correct me if I'm wrong but you forgot the semicolon after age.

void SetAge (int age) [b] { return itsAge = age; }

& toko: Are you reading: Teach Yourself C++ in 21 days [fifth Edition] ?

Yeah thanks for the help. Sorry about the mistake

@ Max_Payne
>>& toko: Are you reading: Teach Yourself C++ in 21 days [fifth Edition] ?

Cool !!
Anyways, that is a good book for starting!!

No, im reading the third edition.

and wuts the for Max_Payne?

No, im reading the third edition.

and wuts the for Max_Payne?

my bad... it was intended for bold as [.b][/b.]. It doesn't have any place in the code.

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.