0% found this document useful (0 votes)
77 views14 pages

Lesson 6 Classes: Objectives

The document discusses classes in C++, explaining that classes allow programmers to represent real-world objects through defining their properties and behaviors, and that classes contain member data and member methods. It covers how to declare a class with public, private, and protected members, how to declare objects of a class, and how to access class members using the dot operator. It also discusses constructors, destructors, accessor and mutator functions, and const member functions.

Uploaded by

Joel Villaruz
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views14 pages

Lesson 6 Classes: Objectives

The document discusses classes in C++, explaining that classes allow programmers to represent real-world objects through defining their properties and behaviors, and that classes contain member data and member methods. It covers how to declare a class with public, private, and protected members, how to declare objects of a class, and how to access class members using the dot operator. It also discusses constructors, destructors, accessor and mutator functions, and const member functions.

Uploaded by

Joel Villaruz
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Lesson 6

Classes

Objectives

Differentiate classes and objects


Define a new class and create objects of that class
Differentiate member methods from member data
Use constructors in declaring and defining a class
Construct interface and implementation on separate files.
Lesson 3 Classes

Classes allow programmers to code real world objects. Unlike


structures, class contains member data (fieldnames) and member methods
(functions). A class is a logical method to organize data and functions in the
same structure. To represent real world objects, we need to specify its
properties and what it can do.

A cat (object) for example can be represented by defining its properties


and what it can do, as reflected in Figure 3.
Cat properties
Has name
Has breed
Has age

Cat properties
Can eat
Can sleep

Figure 3. Cat Object

Classes are declared using keyword class, whose functionality is similar


to that of the keyword struct, but with the possibility of including functions as
members, instead of only data.

Declaring a class

Syntax:

class class_name {
permission_label_1:
member1a;
member1b;
permission_label_2:
member2a;
member2b;
...
};

where class_name is a name for the class (user defined type). The body of the
declaration can contain members, that can be either data or function
declarations, and optionally permission labels, that can be any of these three
keywords: private:, public: or protected:. They make reference to the permission
which the following members acquire:

• private members of a class are accessible only from other members of


their same class or from their "friend" classes.
• protected members are accessible from members of their same class and
friend classes, and also from members of their derived classes.
• Finally, public members are accessible from anywhere the class is visible.

NOTE: If we declare members of a class before including any permission label,


the members are considered private, since it is the default permission that the
members of a class declared with the class keyword acquire.

Member names
Example: char name
To declare as class cat: char breed
int age
class Cat{
public:
void sleep ();
Member methods
void eat ();
private: void eat
char name, breed; void sleep
int age;
}; Figure 4. class Cat

Declaring an object of a class

Declaring an object of a class is the same as declaring an instance of a


primitive data type. For example, the definition int x; specifies that we
create an object x that will inherit all properties of an int data type. Creating
a class can be viewed as creating our own data type.

Syntax:
Class_name class_identifier; Cat properties
garfield.name
Example garfield.breed
Cat garfield; garfield.age

Cat properties
garfield.eat()
garfield.sleep()

Figure 5. Instance of class


To access/manipulate the member of an object

The public members (variables and functions) of the class can be manipulated
using the Dot Operator.

Example:
garfield.age = 4;
garfield.sleep();

Scope resolution operator

The operator :: is called the scope resolution operator and serves a purpose
similar to that of the dot operator. Both the dot operator and the scope
resolution operator are used to tell what a member function is a member of.
However the scope resolution operator :: is used with a class name.

The scope resolution operator is used to define a member function of a class.

Defining a member method

Syntax:

Return_type Class_name::Function_Name (Parameter_list)


{
function_body_statements;
}

Example:

void Cat::sleep( )
{
cout<< “ zzz. Zzzz.. zzz”;
}

Accessor and Mutators

Accessor is function member that allows to read data and usually include the
word get for function name, while Mutator is a function that allows to change
the data and usually include the word set for function name.

Example:
int Cat::get_weight( )
{ ….}

void Cat::set_weight (int weight)


{….}
Listing 3. LabExample3.cpp – Sample Class
#include <iostream.h>

class Person
{
public:
void SetAge(int Age); // Set the age
void SetName(char* chrName); // Set the name
char* GetName(); // get the name

int GetAge(); // get the age

void Greeting1();// Say "Hello!"


void SayName(); // Say "My name is <My Name>"
void Goodbye(); // Say "Good bye!
void SayAge(); // Say " I am <X> years old!"
private:
char* pName;
unsigned int pAge;
};
void Person::SetAge(int Age)
{
pAge = Age;
}
void Person::SetName(char* chrName)

{
pName = chrName;
}
char* Person::GetName()
{
return pName;
}
int Person::GetAge()
{
return pAge;
}
void Person::Greeting1()

{
cout << "Hello!\n";
}
void Person::SayAge()

{
// Check Person age
if (pAge < 2)
// Person is 1 or less years old
cout << "I am a baby!\n";
else
// Person is over 1 years old
cout << "I am " << pAge << " years old!\n";
}
Listing 3. LabExample3.cpp – Sample Class

void Person::SayName()

{
cout << "My name is " << pName << "!\n";
}
void Person::Goodbye()

{
cout << "Good-bye!!\n";
}
int main()

{
// Define our perosn
Person piper;
// Set up piper's age
piper.SetAge(13);
// Give piper's full name
piper.SetName("Piper Halliwell");

// Make piper greet the user


piper.Greeting1();
// Make piper introduce himself
piper.SayName();
// Make piper tell us how old he is
piper.SayAge();
// Make piper dismiss himself
piper.Goodbye();
// end out
return 0;
}

Constructors and Destructors

A constructor is a special member function that is used to initialize the member


data of a class. It can take parameters as needed but not a return value; not
even void. It is a class method with the same name as the class itself. You
may have multiple constructors.

A destructor cleans up after your object and frees any memory you might have
allocated. It always has the same name as your class preceded by a tiled (~).
It has an empty function body; that is its take no action.

All objects must be constructed and destructed. Your compiler creates the
default constructor and destructor which is an empty method.

A class instantiation without parameters is a call to the default constructor.


Ex: Cat Frisky; --- call to default constructor
Cat Frisky(1) – call to defined constructor that takes one parameter.

Listing 4. LabExample4.cpp – Constructor and destructor


#include<iostream.h>
class Cat
{
public:
Cat(int initialAge); //constrcutor
~Cat(); //destructor
int GetAge();
void SetAge( int age);
void Meow();
private:
int itsAge;
};

Cat::Cat(int initialAge) //constructor definition


{
itsAge=initialAge;
}

Cat::~Cat() //destructor definition


{
}

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

void Cat::SetAge(int age)


{
itsAge=age;
}

void Meow()
{
cout<<"meow..";
}

int main()
{
Cat Frisky(5);
cout<<"Firsky is a cat who is"
<<Frisky.GetAge()<<" years old."<<endl;
cout<<"Next year, Frisky will be ";
Frisky.SetAge(6);
cout<<Frisky.GetAge()
<<" years old."<<endl;
return 0;
}
Const Member Functions

Declaring a member function to be const means that you are promising that the
method will not change the value of any of the members of the class. Attach
the const keyword at the end of the function header.

Example: void SomeFunction() const;

Interfaces and Implementation

The interface or the class declaration tells the compiler what the class is, what
data it holds, and what functions it has. It also tells the user how to interact
with the class. Interfaces are usually stored in a .h file.

The implementation of the function definition tells how the function works.
Implementations are stored in the .cpp file.

Inline Implementation

When the definition of the method is provided in the class declaration, it is


called inline implementation.

Listing 5A. LabExample5.h – Cat interface


#include<iostream.h>

class Cat
{
public:
Cat (int initialAge);
~Cat();
int GetAge() const {return itsAge;} //inline
void SetAge (int age) { itsAge=age;}//inline
void Meow() const { cout<<"Meow";} //const method
private:
int itsAge;
};

Listing 5B. LabExample5.cpp - Cat implementation


#include "LABEXAMPLE5.H"
Cat::Cat(int initialAge)
{
itsAge=initialAge;
}

Cat::~Cat()
{
}
Listing 5B. LabExample5.cpp - Cat implementation
int main()
{
Cat Frisky(5);
Frisky.Meow();
cout<<"Frisky is a cat who is "
<<Frisky.GetAge()
<<" years old";
Frisky.Meow();
Frisky.SetAge(7);
cout<<"\n Now Frisky is "
<<Frisky.GetAge()
<<" years old.\n";
return 0;
}

Using Classes with Other Classes as Members

C++ allows definition of more than one class in a file and immediately use this
classes within the same implementation.

In the following example, we will define a rectangle. A rectangle is composed


of lines. A line is defined by two points. A point is defined by an x coordinate
and a y coordinate.

Listing 6A. LabExample6.h – rectangle interface


#include<iostream.h>

class Point
{
public:
void SetX(int x) { itsX=x;}
void SetY(int y) { itsY=y;}
int GetX() const {return itsX;}
int GetY() const {return itsY;}

private:
int itsX;
int itsY;
};

class Rectangle
{
public:
Rectangle(int top, int bottom, int left, int right);
~Rectangle();

int GetTop() const {return itsTop;}


int GetLeft() const {return itsLeft;}
int GetBottom() const {return itsBottom;}
int GetRight() const {return itsRight;}

Point GetUpperLeft() const {return itsUpperLeft;}


Listing 6A. LabExample6.h – rectangle interface
Point GetLowerLeft() const {return itsLowerLeft;}
Point GetUpperRight() const {return itsUpperRight;}
Point GetLowerRight() const {return itsLowerRight;}

void SetUpperLeft(Point Location) {itsUpperLeft = Location;}


void SetLowerLeft(Point Location) {itsLowerLeft = Location;}
void SetUpperRight(Point Location) {itsUpperRight = Location;}
void SetLowerRight(Point Location) {itsLowerRight = Location;}

void SetTop (int top) {itsTop = top;}


void SetLeft (int left) {itsLeft = left;}
void SetBottom (int bottom) {itsBottom = bottom;}
void SetRight (int right) {itsRight = right;}

int GetArea() const;

private:
Point itsUpperLeft;
Point itsUpperRight;
Point itsLowerLeft;
Point itsLowerRight;
int itsTop;
int itsBottom;
int itsLeft;
int itsRight;
};

Listing 6B. LabExample6.cpp – rectangle implementation


#include "LABEXAMPLE6.H"

Rectangle::Rectangle(int top, int bottom, int left, int right)


{
itsTop=top;
itsLeft=left;
itsBottom=bottom;
itsRight=right;

itsUpperLeft.SetX(left);
itsUpperLeft.SetY(top);

itsUpperRight.SetX(right);
itsUpperRight.SetY(top);

itsLowerLeft.SetX(left);
itsLowerLeft.SetY(bottom);

itsLowerRight.SetX(right);
itsLowerRight.SetY(bottom);
}

int Rectangle::GetArea() const


{
int Width = itsRight-itsLeft;
int Height = itsTop - itsBottom;
return (Width*Height);
}

int main()
{
Rectangle MyRectangle(100,20,50,80);

int Area = MyRectangle.GetArea();

cout<<"Area: "<<Area;
cout<<"\n UpperLeft X Coordinate: "
<<MyRectangle.GetUpperLeft().GetX() << endl;
return 0;
}

Static Member Variable

It is a variable that is shared by all objects of a class. Static functions


can be invoked in the normal way, using a calling object of the class. However,
it is more common and clearer to invoke static function using the class name
and scope resolution operator, as in the following example:

CRectangle::get_area( );

Initializing static member variables

Each static member variable must be initialized outside the class


definition and must only be initialized out: Syntax as follows:

int Crectangle::x = 0;

Listing 7. LabExample7.cpp. Static member functions


class CRectangle
{
public:
void set_values(int,int);
static int get_area();
static int get_volume();
private:
static int x,y;
static int height;
static int compute_area();
static int compute_volume();
};

int CRectangle::height=10;
int CRectangle::x = 0;
int CRectangle::y = 0;
Listing 7. LabExample7.cpp. Static member functions
void main()
{
int area, volume, a, b;
CRectangle rect, square;

cout <<"Enter lengths of rectangle\n";


cin>>a >>b;

rect.set_values(a,b);

area=CRectangle::get_area();
volume=CRectangle::get_volume();

cout<<"Area of Rectangle: " <<area<<endl;


cout<<"Volume of Rectangle: "<<volume<<endl;

cout<<"\nEnter length of square\n";


cin>> a >> b;

square.set_values(a,b);

area=CRectangle::get_area();
volume=CRectangle::get_volume();

cout<<"Area of Square: " <<area<<endl;


cout<<"Volume of Square: "<<volume<<endl;
}

void CRectangle::set_values(int a, int b)


{
x=a;
y=b;
}

int CRectangle::get_area ()
{
return compute_area();
}

int CRectangle::get_volume ()
{
return compute_volume();
}

int CRectangle::compute_area()
{
return (x*y);
}

int CRectangle::compute_volume()
{
return (compute_area() * height);
}
Arrays of Objects
Objects can also be represented in arrays. See Listing 7 for example.

Listing 8. program fragment – Arrays of objects


Cat Litter[5];
int i;
for(i =0; i<5; i++)
Litter[i].SetAge(2*i+1);
for(i =0; i<5; i++)
{
cout<<" Cat # "<<i + 1<<":"
<<Liter[i].GetAge();
}
Laboratory Exercise

Exercise # Date

Name Course/Section

Problem Statement:
Design a class that can be used to represent types of food. A type of food is classified as
basic or prepared. Basic foods are further classified as Dairy, Meat, Fruit, Vegetable, or
Grain. The services provided by the class include the ability to enter data for new food,
change data for new food, display existing data for new food. Create a program that will
allow the user to enter data for four food items and display the entered data. Provide a
menu for selection of services and allow user input for program rerun and/or termination.

Laboratory Exercise Score Sheet

Criteria Score

1 Class declaration is in a .h file 10

2 Class implementation is in a .cpp file 10

3 Program contains accessor 5

4 Program contains mutator 5

5 Correct class declaration and definition 15

6 Appropriate methods were defined 15

7 Contains error handling procedures 10

8 Accepts user input 10

9 Program has provisions for user requested termination 10

10 Program has comments, variable names are descriptive of 10


what they hold

Total

Checked by:

Instructor

You might also like