[go: up one dir, main page]

0% found this document useful (0 votes)
92 views16 pages

03 - Classes and Objects

This document provides an overview of classes and objects in C++. It discusses key concepts like classes serving as templates that define data and functions for objects. An object is an instance of a class that is used in a program. Classes allow defining variables like arrays of objects. Access control specifiers like public, private, and protected determine which class members can be accessed from outside the class. Methods can be defined both inside and outside the class. Dynamic memory allocation is used to create objects at runtime.

Uploaded by

Engin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views16 pages

03 - Classes and Objects

This document provides an overview of classes and objects in C++. It discusses key concepts like classes serving as templates that define data and functions for objects. An object is an instance of a class that is used in a program. Classes allow defining variables like arrays of objects. Access control specifiers like public, private, and protected determine which class members can be accessed from outside the class. Methods can be defined both inside and outside the class. Dynamic memory allocation is used to create objects at runtime.

Uploaded by

Engin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lecture 3 :

Classes and Objects

Outline
• Classes and Objects
• C++ Terminology
• Dynamically allocated Objects
• Arrays of Objects
• Controlling Access to Member Attributes
• Friend Functions and Friend Classes
• this Pointer

1
Classes and Objects
 Real-world object = Attributes + Abilities

 Programming object = Data + Functions

 Class is a data type which is used to define objects.

 A class serves as a model description.

 It specifies what data and what functions will be included in


objects of that class.

3.3

C++ TERMINOLOGY
 A class is a grouping of data and functions.
 A class is very much like a struct type as used in C.
 Writing a class doesn’t create any objects.

 An object is an instance of a class, which is similar to a variable.


 An object is what you actually use in a program.

 An attribute is a member data of a class.


 Example; Name of a student, coordinates of a point.

 A method (message) is a member function contained within the


class.

3.4

2
Example : Point class
 A Point class can be written in a graphics program.
 The Point class will have two properties:
• x and y coordinates.

 The Point class can have the following abilities :


• move function : Moves to a location.
• print function : Shows the coordinates on the screen.
• is_zero function : Checks whether it is on the zero point (0,0)
or not.

3.5

Point class declaration


 Point class contains x and y member data. Their access type is
private by defult.
 Class also contains member functions, which are declared as public
access.

class Point { // Declaration of Point Class


Data int x,y; // Current x and y coordinates

public: // public access allowed


void move(int, int); // A function to move to a new point
Functions void print(); // To print the coordinates on screen
bool is_zero(); // Is the point on the zero point (0,0) ?
};

3.6

3
Member Functions of Point class
:: is scope operator. The move function is a member of Point class.

// A function to move the points


void Point :: move(int new_x, int new_y) {
x = new_x; // assigns new value to x coordinate
y = new_y; // assigns new value to y coordinate
}

// Print the coordinates on the screen


void Point :: print() {
cout << "X= " << x << ", Y= " << y << endl;
}

// Check whether the point is on the zero point(0,0)


bool Point :: is_zero() {
return (x == 0) && (y == 0);
// returns true or false
}
3.7

 Classes can be used to define variables, similar to built-in data types


(int, float, char etc.).
 Example : In main program, we can define Point variables (objects) using the
class.

int main() {
Point P1, P2; // Two object variables are defined.

P1.move(100,50); // P1 moves to (100,50) location


P1.print();
if ( P1.is_zero() )
cout << "P1 is on zero point" << endl;
else
cout << "P1 is NOT on zero point" << endl;
//----------------------------------------------------------------------
P2.move(0,0); // P2 moves to (0,0)
if( P2.is_zero() )
cout << "P2 is on zero point" << endl;
else
cout << "P2 is NOT on zero point" << endl;
}

3.8

4
Defining Methods inside a Class
 Any function code written inside a class definition is considered
automatically an inline function by the compiler.
 Example: is_zero function of Point class can be defined inside the class.
The "inline" keyword is not written.
 Inline syntax should be preferred only for short functions.

class Point{ // Declaration of Point Class


int x,y; // Properties: x and y coordinates
public:
void move(int, int);
void print();

bool is_zero() // Function is written inline


{
return (x == 0) && (y == 0);
}
};

3.9

Defining Dynamic Objects


 Example : Two pointers (ptr1 and ptr2) to Point objects are defined and
dynamically allocated.

int main() {
// Allocating memory for two Point objects
Point *ptr1 = new Point;
Point *ptr2 = new Point;

ptr1->move(50, 50);
ptr1->print();

ptr2->move(100, 150);
if( ptr2->is_zero() )
cout << " Object is on zero." << endl;
else
cout << " Object is NOT on zero." << endl;

// Releasing the memory


delete ptr1;
delete ptr2;
}
3.10

5
Defining Array of Objects
Example: An array is defined with 10 elements of type Point.

int main() {
Point array[10]; // defining an array with 10 objects

array[0].move(15, 40);
// move message to the first element (index 0)

array[1].move(75, 35);
// move message to the second element (index 1)

for (int i = 0; i < 10; i++)


// print message to all objects in the array
array[i].print();
}

3.11

Controlling Access to Members


 The labels public: , private: , protected: are used to control access to
member data and functions of a class.

 Each label applies until the next label, or until the end of class
declaration.

 Public members may be accessed from any place in the program.

• Private members can be accessed only by member functions of that class.


It is the default access mode.
• Private data are hidden, and can not be used by main program or by other
classes.

• Protected is similar to private, and related to inheritance.

3.12

6
Example: Controlling Access to Members
• Only the public members (data and function) of the class A can be
accessed from outside of class such as in main.
• The f1,f2,f3 functions can access to all member data (x,y,z).

#include <iostream> int main()


using namespace std; {
A a; // Object definition
class A
{ a.x = 10; // Compiler error : x is private
// Member data a.y = 20; // Compiler error : y is protected
private : int x; a.z = 30; // z is public
protected : int y;
public : int z; a.f1(); // Compiler error : f1 is private
a.f2(); // Compiler error : f2 is protected
// Member functions a.f3(); // f3 is public
private : void f1() { } }
protected : void f2() { }
public : void f3() { }
};
3.13

Point class
 The purpose of public members is to present a view of the services
(functions) the class provides.
 This set of services forms the public interface of the class.
 The private members are not accessible to the clients of a class.

UML class diagram

Point Name of class

- x : int Private member data


- y : int (- symbol indicates private access)

+ move(int, int) : void


+ print() : void Interface :
+ is_zero() : bool Public member functions
(+ symbol indicates public access)

3.14

7
Example
In the following version of Point class, the return type of the move
function is changed from void to bool.

class Point {
private:
int x,y; // private members: x and y coordinates

public: // public members


bool move(int, int);
void print();
bool is_zero();
};

3.15

Restriction: Clients of the class can not move a point outside a


window with a size of 500x300 pixels.

// A function to move the points

bool Point::move(int new_x, int new_y)


{
if ( new_x > 0 && new_x < 500 &&
new_y > 0 && new_y < 300)
{
// assign new values
x = new_x;
y = new_y;
return true;
// input values are accepted
}

return false; // input values are not accepted


}

3.16

8
The move function returns a boolean value to inform
whether the input values are accepted or not.

int main()
{
Point p1; // p1 object is defined
int x,y;
// Two variables to read coordinate values from keyboard

cout << " Give x and y coordinates “;


cin >> x >> y; // Read two values from keyboard

if( p1.move(x,y) ) // send move message and check the result


p1.print(); // If result is true, print coordinates on screen
else
cout << endl << "Input values are not accepted";
}

3.17

Example : private data members


 If the access label is not written for a member data or function, then they are
private by default.
 In Point class, x and y data members are private by default.
 It is not possible to assign a value to x or y directly outside the class.
 Also, displaying them directly is not allowed.

class Point {
int x,y; // private member data by default
public:
bool move(int, int);
void print();
};
int main() {
Point p1;
p1.move(100,50);
p1.print();
p1.x = 70; // Compiler error
p1.y = 130; // Compiler error
cout << p1.x << endl; // Compiler error
cout << p1.y << endl; // Compiler error
}
3.18

9
Example : public data members

If x and y members are defined as public, there will be no access restrictions.

class Point {
public:
int x,y;
bool move(int, int);
void print();

};
int main() {
Point p1;
p1.move(100,50);
p1.print();
p1.x = 70; // Allowed
p1.y = 130; // Allowed
cout << p1.x << endl; // Allowed
cout << p1.y << endl; // Allowed
}
3.19

Example: private function members


Private member functions are not allowed to call directly such as from main.

class Point{
bool move(int, int);
// private member function by default
public:
int x,y;
void print();

};

int main() {
Point p1;
p1.move(100,50); // Compiler error!
p1.print();
p1.x = 70;
p1.y = 130;
cout << p1.x << endl;
cout << p1.y << endl;
}
3.20

10
Friend Classes
 A function or an entire class may be declared to be a friend of another class.
 A friend of a class has the right to access all members
(private, protected or public) of the given class.

class A {
friend class B;
Class B is a
private:// private members of A friend of class A.
int i;

public: // public members of A


void func1();
};

3.21

Class B can access private members of class A.


class B {
int j;
public:
void func2(A x)
{
cout << j << endl;;
cout << x.i; }
}
};

Object a is passed to function of object b.

int main() {
A a;
B b;
b.func2(a);
}

3.22

11
Friend Functions
• A friend function is not a member of any class.
• A friend function has the right to access all members (private, protected
or public) of the class.

class Point {
friend void set_to_zero(Point &); // Friend function of Point

int x,y; // private members: x and y coordinates

public: // public members


bool move(int, int);
void print();
bool is_zero();
};

3.23

The set_to_zero function can access all members of Point class.

// Non-member function
// Not a member of any class

void set_to_zero(Point &p)


{
p.x = 0;
p.y = 0;
}

Object p1 is passed to set_to_zero function.

int main() {
Point p1;
set_to_zero(p1);
}

3.24

12
Data spaces and Function codes
 Each object has its own data space in memory.
 When an object is defined, memory is allocated only for its data members.
 Each object of the same class uses the same function code.

Data spaces Function codes


(distinct) (common)

x=100 move
point1
y=50

print

x=200
point2
y=300
is_zero

3.25

The this Pointer


 For every class definition, the C++ compiler maintains a special
built-in pointer, called the this pointer.

 When a member function is called, this pointer contains the self


address of the object.

 Example: point1 and point2 objects have different this pointers.


 The member functions can access data members using the
pointer this.

3.26

13
In the following examples, usage of the this pointer is optional
(i.e. not required).

void Point::move(int new_x, int new_y)


{ // assigns new values to coordinates
this->x = new_x;
this->y = new_y;
}

void Point::print()
{
cout << this->x << " " << this->y << endl;
}

3.27

Example
 The find_max_distance() member function takes another Point object as
argument.
 It compares distance of itself and the distance of argument object.
 Then it returns the address of the object, which has the largest distance
from the origin.

Point * Point::find_max_distance (Point & p) {


int distance1, distance2;
distance1 = sqrt ( ( x * x) + (y * y) );
distance2 = sqrt ( ( p.x * p.x) + (p.y * p.y) );

if (distance1 > distance2 )


return this; // Object returns its own address.
else
return &p; // Else returns the address of the p object.
}

3.28

14
int main()
{
Point P1, P2; // Two objects: P1 , P2

P1.move(100,50);
P2.move(20,65);

Point * a; // a is a pointer that will point one of them.


a = P1. find_max_distance(P2);

// Alternative command
// a = P2. find_max_distance(P1);

a->print();
// the point that has the largest distance is printed on screen
}

3.29

Alternative: Calling a non-member function


class Point {
public:
int x,y; // Data members are made public.
…….
};

// Non-member function
Point * find_max_distance (Point & p1, Point & p2) {
int distance1 = sqrt ( ( p1.x * p1.x) + (p1.y * p1.y) );
int distance2 = sqrt ( ( p2.x * p2.x) + (p2.y * p2.y) );
if (distance1 > distance2 ) return &p1;
else return &p2;
}

int main() {
Point P1,P2;
P1.move(100,50);
P2.move(20,65);
Point * a;
a = find_max_distance(P1, P2);
a->print();
}
3.30

15
Example: Member data and argument with same name
When parameters of a function has the same names as the data members of class,
the this pointer is required to be used in the function.

class Point{
int x,y; // private members: x and y coordinates
public: // public members
bool move(int x, int y);
…..
};

bool Point::move(int x, int y) // parameters has the same name as


{ // data members x and y
if( x > 0 && x < 500 && y > 0 && y < 300) {
this->x = x; // assigns given x value to member x
this->y = y; // assigns given y value to member y
return true; // input values are accepted
}
return false; // input values are not accepted
}

16

You might also like