0% found this document useful (0 votes)
43 views47 pages

Classes

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

Classes

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

Lecture No.

7:
Concepts of OOP
Classes, Objects, Access Specifiers,
Constructors and Destructors
C++ What is OOP?
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and functions.
• Object-oriented programming has several advantages over procedural
programming:
– OOP is faster and easier to execute
– OOP provides a clear structure for the programs
– OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
– OOP makes it possible to create full reusable applications with less code and
shorter development time

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 2


C++ What are Classes and Objects?
• Classes and objects are the two main aspects of object-oriented programming.
• Look at the following illustration to see the difference between class and objects:

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 3


C++ Classes/Objects
• C++ is an object-oriented programming language.
• Everything in C++ is associated with classes and objects, along with
its attributes and methods. For example: in real life, a car is an
object. The car has attributes, such as weight and color, and
methods, such as drive and brake.
• Attributes and methods are basically variables and functions that
belongs to the class. These are often referred to as "class
members".
• A class is a user-defined data type that we can use in our program,
and it works as an object constructor, or a "blueprint" for creating
objects.

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 4


Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 5


Create an Object
• In C++, an object is created from a class. We have already created the
class named MyClass, so now we can use this to create objects.
• To create an object of MyClass, specify the class name, followed by the
object name.
• To access the class attributes (myNum and myString), use the dot
syntax (.) on the object:

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 6


Example:
Create an object called "myObj" and access the attributes:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0; } From Problem Analysis to Program Design, Sixth Edition
C++ Programming: 7
Classes
• Object-oriented design (OOD):
a problem solving methodology
• Objects:
components of a solution
• Class:
a collection of a fixed number of components
• Member:
a component of a class

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 8


Classes (cont’d.)
• Class definition:
– Defines a data type; no memory is allocated
– Don’t forget the semicolon after the closing brace
• Syntax:

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 9


Classes (cont’d.)
• Class member can be a variable or a function
• If a member of a class is a variable
– It is declared like any other variable
– You cannot initialize a variable when you declare it
• If a member of a class is a function
– Function prototype is listed
– Function members can (directly) access any
member of the class

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 10


Access Specifiers
Example: class MyClass { // The class
public: // Access specifier
// class members goes here
};

Access specifiers define how the members (attributes and methods) of a class
can be accessed.

In the example above, the members are public - which means that they can be
accessed and modified from outside the code.

However, what if we want members to be private and hidden from the outside
world?
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 11
Access Specifiers
• Three categories of class members:
– private (default)
• members cannot be accessed (or viewed) from outside
the class
• public
• members are accessible from outside the class
• Protected
• members cannot be accessed from outside the class,
however, they can be accessed in inherited classes. You
will learn more about Inheritance later.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 12
Example

In the following example, we demonstrate the differences between public


and private members:

class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
If you try to access a private member, an error occurs:

error: y is private
Public:
#include <iostream>
using namespace std;

class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};

// Member functions definitions


double Line::getLength(void) {
return length ;
}

void Line::setLength( double len) {


length = len;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

// set line length without member function


line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;

return 0;
}
Private:
#include <iostream>
using namespace std;

class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );

private:
double width;
};

// Member functions definitions


double Box::getWidth(void) {
return width ;
}

void Box::setWidth( double wid ) {


width = wid;
}

// Main function for the program


int main() {
Box box;

// set box length without member function


box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;

// set box width without member function


// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;

return 0;
}
Protected:
#include <iostream>
using namespace std;

class Box {
protected:
double width;
};

class SmallBox:Box { // SmallBox is the derived class.


public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};

// Member functions of child class


double SmallBox::getSmallWidth(void) {
return width ;
}

void SmallBox::setSmallWidth( double wid ) {


width = wid;
}

// Main function for the program


int main() {
SmallBox box;

// set box width using member function


box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;

return 0;
}
Variable (Object) Declaration
• Once defined, you can declare variables of
that class type
clockType myClock;

• A class variable is called a class object or


class instance

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 17


Accessing Class Members
• Once an object is declared, it can access the
public members of the class
• Syntax:

– The dot (.) is the member access operator


• If an object is declared in the definition of a
member function of the class, it can access
the public and private members

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 18


#include <iostream>
using namespace std;

class Box {
Example
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Built-in Operations on Classes
• Most of C++’s built-in operations do not apply to
classes
– Arithmetic operators cannot be used on class objects
unless the operators are overloaded
– Cannot use relational operators to compare two class
objects for equality
• Built-in operations that are valid for class objects:
– Member access (.)
– Assignment (=)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 20


Assignment Operator and Classes

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 21


Class Scope
• An object can be automatic or static
– Automatic: created when the declaration is
reached and destroyed when the surrounding
block is exited
– Static: created when the declaration is reached
and destroyed when the program terminates
• Object has the same scope as other variables

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 22


Class Scope (cont’d.)
• A member of the class is local to the
class
• Can access a class member outside the
class by using the class object name and
the member access operator (.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 23


Functions and Classes
• Objects can be passed as parameters to
functions and returned as function values
• As parameters to functions
– Objects can be passed by value or by reference
• If an object is passed by value
– Contents of data members of the actual
parameter are copied into the corresponding data
members of the formal parameter

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 24


Reference Parameters and Class
Objects (Variables)
• Passing by value might require a large amount
of storage space and a considerable amount of
computer time to copy the value of the actual
parameter into the formal parameter
• If a variable is passed by reference
– The formal parameter receives only the address of
the actual parameter

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 25


Reference Parameters and Class
Objects (Variables) (cont’d.)
• Pass by reference is an efficient way to pass a
variable as a parameter
– Problem: when passing by reference, the actual
parameter changes when formal parameter
changes
– Solution: use const in the formal parameter
declaration

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 26


Implementation of Member
Functions
• Must write the code for functions defined as
function prototypes
• Prototypes are left in the class to keep the
class smaller and to hide the implementation
• To access identifiers local to the class, use the
scope resolution operator ::

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 27


Implementation of Member
Functions (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 28


Implementation of Member
Functions (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 29


Implementation of Member
Functions (cont’d.)
• Once a class is properly defined and
implemented, it can be used in a program
– A program that uses/manipulates objects of a
class is called a client of that class
• When you declare objects of the class
clockType, each object has its own copy of
the member variables (hr, min, and sec)
• Called instance variables of the class
– Every object has its own instance of the data
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 30
#include <iostream>
using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}

void Box::setLength( double len ) {


length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Order of public and private
Members of a Class
• C++ has no fixed order in which to declare
public and private members
• By default, all members of a class are
private
• Use the member access specifier public to
make a member available for public access

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 32


Constructors
• Use constructors to guarantee that member
variables of a class are initialized
• Two types of constructors:
– With parameters
– Without parameters (default constructor)
– Name of a constructor = name of the class
– A constructor has no type

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 33


Constructors (cont’d.)
• A class can have more than one constructor
– Each must have a different formal parameter list
• Constructors execute automatically when a class
object enters its scope
• They cannot be called like other functions
• Which constructor executes depends on the types
of values passed to the class object when the class
object is declared
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 34
Constructors (Example)
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
} };
int main() {
MyClass myObj; // Create an object of MyClass (this will call the
constructor)
return 0; }
A constructor in C++ is a special method that is automatically called
when an object of a class is created.
To create a constructor, use the same name as the class, followed by
parentheses ():
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 35
Invoking a Constructor

• A constructor is automatically executed when


a class variable is declared
• Because a class may have more than one
constructor, you can invoke a specific
constructor

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 36


Invoking the Default Constructor
• To invoke the default constructor:

• Example:
clockType yourClock;

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 37


Constructor Parameters
Constructors can also take parameters (just like regular functions),
which can be useful for setting initial values for attributes.

The following class have brand, model and year attributes, and a
constructor with different parameters. Inside the constructor we set
the attributes equal to the constructor parameters (brand=x, etc).
When we call the constructor (by creating an object of the class), we
pass parameters to the constructor, which will set the value of the
corresponding attributes to the same:

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 38


class Car { // The class

Constructor Parameters
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
} C++ Programming: From Problem Analysis to Program Design, Sixth Edition 39
Invoking a Constructor with
Parameters
• Syntax:

• Number and type of arguments should match


the formal parameters (in the order given) of
one of the constructors
– Otherwise, C++ uses type conversion and looks for
the best match
– Any ambiguity causes a compile-time error
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 40
Constructors and Default
Parameters
• A constructor can have default parameters
– Rules for declaring formal parameters are the
same as for declaring default formal parameters in
a function
– Actual parameters are passed according to same
rules for functions
• Default constructor: a constructor with no
parameters or with all default parameters

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 41


#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}
//Parameterized Constructors
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line(10.0);

// get initially set length.


cout << "Length of line : " << line.getLength() <<endl;

// set line length again


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0; }
The Class Destructor
•A destructor is a special member function of a class
that is executed whenever an object of it's class
goes out of scope or whenever the delete
expression is applied to a pointer to the object of
that class.
•A destructor will have exact same name as the
class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters.
Destructor can be very useful for releasing
resources before coming out of the program like
closing files, releasing memories etc.
//The Class Destructor
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
Line::~Line(void) {
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}
Classes and Constructors: A
Precaution
• If a class has no constructor(s), C++ provides
the default constructor
– However, object declared is still uninitialized
• If a class includes constructor(s) with
parameter(s), but not the default constructor
– C++ does not provide the default constructor

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 46


Destructors
• Destructors are functions without any type
• The name of a destructor is the character '~'
followed by class name
– For example:
~clockType();
• A class can have only one destructor
– The destructor has no parameters
• Destructor automatically executes when the
class object goes out of scope
C++ Programming: From Problem Analysis to Program Design, Sixth Edition 47

You might also like