[go: up one dir, main page]

0% found this document useful (0 votes)
60 views60 pages

C++ Basics of OO Programming: User-Defined Class

The document discusses the basics of object-oriented programming (OOP) in C++. It introduces key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that classes provide templates for creating objects with common attributes and behaviors. The document provides examples of how classes model real-world objects and defines a Circle class to demonstrate class features like data fields, constructors and methods.

Uploaded by

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

C++ Basics of OO Programming: User-Defined Class

The document discusses the basics of object-oriented programming (OOP) in C++. It introduces key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that classes provide templates for creating objects with common attributes and behaviors. The document provides examples of how classes model real-world objects and defines a Circle class to demonstrate class features like data fields, constructors and methods.

Uploaded by

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

C++ Basics of OO Programming

User-defined Class

Chapter 6- Basics of OOP


Chapter Objectives
Basic OOP Concepts
The concept of Classes and Objects
Defining Classes
Constructor Methods
Member functions
Derived Classes( Class Inheritance)
Method Overloading and Overriding (Redefining)

Chapter 5- Introduction to OOP Programming - C++ 2


Object Oriented Programming -OOP
The idea of OO programming is to model the features (aka properties or
attributes) and behavior of real-world objects in the problem domain by
software objects (aka instances).

The class construct provides a template (or blueprint) for the creation of
objects.

Classes specify what attributes and behavior an object may have.

May create many objects from a given class


- Each object will have its own attribute, but will have identical
behavior.
Chapter 5- Introduction to OOP Programming - C++ 3
Important Concepts for OO Programming
Abstraction
Extract only the relevant properties of a real-world for developing a
class while ignoring the non-essentials
Encapsulation
Group the attributes and behavior of an object together in a single
data structure known as a class
Information Hiding
Hide and protect essential information of the class from outside
functions through a controlled interface
Chapter 5- Introduction to OOP Programming - C++ 4
OO Feature - Abstraction
• For any problem, extract the relevant real-world object properties for software
objects, while ignoring non-essentials
– Defines a view of the software object
• Example - car
– Car dealer views a car from selling features standpoint
• Price, length of warranty, color, …
– Mechanic views a car from systems maintenance standpoint
• Size of the oil filter, type of spark plugs, …
Price? Oil change?

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 5


Encapsulation and Information Hiding
• Steps
– Decompose an object into parts
– Hide and protect essential information
– Supply an interface that allows an object to be accessed in a controlled and useful
manner
• Interface means that the internal representation of a class can be changed without
affecting other system parts

• Example - Radio
– Interface consists of controls and power and antenna connectors
• The details of how it works is hidden
– To install and use a radio
• Do not need to know anything about the radio’s electronics 6

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++


OO Feature - Modularity
• Dividing an object into smaller pieces or “modules” so that the object is easier to
understand and manipulate.

• Most complex systems are modular

• Example - Car can be decomposed into subsystems


– Cooling system
• Radiator Thermostat Water pump

– Ignition system
• Battery Starter motor Spark plugs
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 7
OO Feature - Hierarchy
• Hierarchy
– Ranking or ordering of objects based on some relationship between them

• Helps us understand complex systems


– Example - a company hierarchy helps employees understand the company and
their positions within it

• For complex systems, a useful way of ordering similar abstractions is a taxonomy


from least general to most general

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 8


Inheritance Hierarchies

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 9


The 3 main OOP Characteristics
• Data Encapsulation and Information Hiding
– Data and functions are said to be encapsulated into a single entity – the class
– Data is concealed within a class, so that it cannot be accessed mistakenly by functions
outside the class.

• Inheritance

• Polymorphism

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 10


The 3 Main OOP Characteristics

• Data Encapsulation and Information Hiding

• Inheritance
– The process of creating new classes, called derived classes, from existing
classes or base classes creating a hierarchy of parent classes and child classes.
– The child classes inherit the attributes and behavior of the parent classes.

• Polymorphism

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 11


The 3 Main OOP Characteristics
• Data Encapsulation and Data Hiding

• Inheritance

• Polymorphism
– Generally, the ability to appear in many forms
– More specifically, in OOP, it is the ability to redefine methods for derived
classes
– Ability to process objects differently depending on their data type or class
– Giving different meanings to the same thing

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 12


Class Construct

Allows the definition of specific objects with defined


attributes (data) and behavior (functions)
→ Essence of object-oriented programming

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 13


Classes
Classes are language constructs that allow the definition and
creation of objects of the same type.

A class uses variables to define data fields and functions to define


behaviors.

Additionally, a class provides a special type of function, known as a


constructor, which is invoked to create new objects from the class
definition.
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 14
A class describes a set of objects with the same behavior.

You may create the Car class to represent cars as objects

To define a class, you must specify the behavior by providing implementations for
the member functions, and by defining the data members for the objects …
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 15
Classes
class Circle
{
public:
// The radius of this circle
double radius; Data field

// Construct a circle object


Circle()
{
radius = 1;
} Constructors

// Construct a circle object


Circle(double newRadius)
{
radius = newRadius;
}

// Return the area of this circle


double getArea() Function
{
return radius * radius * 3.14159;
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ } 16
};
#include <iostream>
using namespace std;
int main()
class Circle
{
{
Circle circle1(1.0);
private:
Circle circle2(25);
// The radius of this circle
Circle circle3(125);
double radius;
cout << "The area of the circle of radius "
public:
" 1.0 is " << circle1.getArea() << endl;
// Construct a default circle object
cout << "The area of the circle of radius "
Circle()
“25 is " << circle2.getArea() << endl;
{
cout << "The area of the circle of radius "
radius = 1;
“125 is " << circle3.getArea() << endl;
}
return 0;
// Construct a circle object
}
Circle(double newRadius)
{
radius = newRadius;
}

// Return the area of this circle


double getArea()
{
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++
return radius * radius * 3.14159; 17

}
}; // Must place a semicolon here
OO Feature - Objects
• An object is almost anything with the following characteristics
– Name
– Properties
– Operations
– The ability to act upon receiving a “message” – being called by a function or
another object.
• Basic message types
– Directive to object to perform an action
– Request to object to change one of its properties

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 18


Class Data Types

• The Class construct

- Actually allows programmers to define new data types for


representing information

- Class type objects can have both attribute and behavior


components

- Provides the object-oriented programming in C++

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 19


Terminology
Object behaviours
- Realized in C++ via member functions (aka methods)

- Methods are public – accessible from outside the class

Object attributes
- Are known as data members in C++

- Attributes are private – only accessible to class members

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 20


Terminology Cont’d…
Any part of the program should be able to call the member functions – so they
are in the public section.

Data members are defined in the private section of the class.


- Only member functions of the class can access them.

- They are hidden from the rest of the program.

So that outside functions may access the data members, we provide special
functions in the class to form an interface – accessors and mutators.

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 21


Object Names
You assign an object a name when creating the object.

A special class function called the class constructor is invoked when an object is created.

The syntax to create an object using the constructor is

ClassName objectName;

For example,
Circle circle1; Note that a constructor has the same
name as the class.
for some class Circle

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 22


Access Operator
After an object is created, its data can be accessed and its functions invoked using the dot
operator .

objectName.dataField references a data field of the object.

objectName.function(arguments) invokes a function of the object.

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 23


Private versus Public
• Public member functions allow “clients” to operate on the objects of a
class.

• May have private member functions


– If member functions need to call another function that is part or not
part of the class then it should be private

• Apply due care when defining public access

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 24


Private versus Public
Information hiding recommends that data members should be private

- not freely accessible by clients


So, in order for clients to read/write the values of the data members
of an object, must provide so-called get and set functions ( aka accessors
and mutators)

- get – read value


- set – write value
The only way clients may access the data members.
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 25
Accessor and Mutator
Colloquially, a get function is referred to as a getter (or accessor), and a set
function is referred to as a setter (or mutator).

A get function has the following signature (Only a convention!):


returnType getPropertyName()

A set function has the following signature (only a convention!):


public void setPropertyName(dataType propertyValue)

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 26


Classes
class NameOfClass
{
public:
// The “public” interface – available to clients
// Here we define the public methods of the class

private:
// the data members – only accessible by functions of the class
};

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 27


Remember

Every class object


- Has its own data members

- Has its own member functions (which are the same as other objects of the same
class have)

- When a member function accesses a data member


By default the function accesses the data member of
the object to which it belongs!

- No special notation needed

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 28


Next three slides illustrate the conventional concept
of classes including general methods like getData()
and showData().

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 29


class Person
{
private: string name;
int age;

public: void setData()


{
cout << “\nEnter name:”; cin >> name;
cout << “\nEnter age:”; cin >> age;
}
void getData()
{
cout << “\nName:” << name << ”\t\tAge:” << age;
}
};

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 30


No constructor here!
// Statements to define instances of the Person class:
// Objects named Ivan and Elena

Person Ivan, Elena;

// Array of Person objects named family with size of 5

Person family[5];

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 31


// Statements to call members (data and methods) of the Person
class:

// Private members cannot be called from outside the class


 
// Public members can be called from inside and outside the class

Ivan.setData();
Ivan.getData(); // OK

Ivan.age = 19; // Error

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 32


Example – better!

class Person
{
private: string name;
unsigned age;
public:
string getName() { return name; }
unsigned getAge() { return age; }
void setName(string par){name = par;}
void setAge(unsigned par){age = par;}
};

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 33


Constructors
• Special member function
– Same name as class name

• Constructor is invoked each time an object is declared for a


given class

• Initializes object

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 34


Constructor

The constructor has exactly the same name as the defining class.

A class normally provides a constructor without arguments - default constructor.

Like regular functions, constructors can be overloaded (i.e. multiple constructors with
the same name but different signatures), making it easy to construct objects with
different initial data values.

A class may be declared without constructors.

 - In this case, a default constructor, is provided automatically but only if no


constructors are explicitly declared in the class.
Chapter 5- Introduction to OOP Programming - C++ 35
Constructing with Arguments
• Constructors may be overloaded

• The syntax to declare an object using a constructor with parameters is

• ClassName objectName(parameters);

• For example, the following declaration creates an object named circle2


by invoking the Circle class’s constructor with a specified radius 5.5.

• Circle circle2(5.5);
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 36
Classes

To define a class you write:

class NameOfClass
{
public:
// the public interface
private:
// the data members
};
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 37
Classes – definition syntax
Any part of the program should be able to call the
member functions – so they are in the public section.

class NameOfClass
{
public:
// the public interface
private:
// the data members
};
Data members are defined in the private section of the class.
Only member functions of the class can access them.
- They are hidden from the rest of the program.
Chapter 5- Introduction to OOP Programming - C++ 38
Here is the C++ syntax for a CashRegister class definition:

class CashRegister
{
public:
void clear();
void add_item(double price);
double get_total() const;
int get_count() const;
private:
// data members will go here
};
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 39
The public interface has the four activities that we decided this
object should support.
class CashRegister
{
public:
void clear();
void add_item(double price);
double get_total() const;
int get_count() const;
private:
// data members will go here
};

Notice that these are just declarations. They will


be defined later.
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 40
You call the member functions by first creating a variable of
type CashRegister and then using the dot notation:

CashRegister register1;
...
register1.clear();
...
register1.add_item(1.95);

Because these are mutators, the data members in the object


will be changed.
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 41
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 42
Every CashRegister object has its own copy of the data members 43
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++
The Philosophy of Private Data Members
More “secure” programs – not “abused” by clients.
Example: if we use private, we can write a mutator for item_count so
that item_count cannot be set to a negative value.

If item_count were public, it could be directly set to a negative value by


some misguided (or worse, devious) programmer.

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 44


The interface for our class:

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 45


Implementing the Member Functions
The details of the add_item member as a regular function:

void add_item(double price)


{
item_count++;
total_price = total_price + price;
}

However, to specify that a function is a member function of your class


you must write

CashRegister::

in front of the member function’s name:


CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 46
void CashRegister::add_item(double price)
{
item_count++;
total_price = total_price + price;
}

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 47


Implementing the Member Functions
Use CashRegister:: only when defining the function outside the class –
not in the class definition.
class CashRegister
{
public:
... Not here
private:
... Only here
};
void CashRegister::add_item(double price)
{
item_count++; Function definition
total_price = total_price + price;
}
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 48
Implementing the Member Functions

Often, separate the class definition from the implementation

- Put in separate files

- Class definition in a header file with .h extension

- Implementation in a source file with a .cpp extension

- In main(), have
#include “ClassName.h”

Chapter 5- Introduction to OOP Programming - C++ 49


Constructors
The name of a constructor is identical to the name of its class

class CashRegister
{
public:
CashRegister(); // A constructor
...
};

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 50


Constructors

There must be no return type, not even void.

class CashRegister
{
public:
CashRegister(); // A constructor
...
};
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 51
Constructors

And, of course, you must define the constructor.


CashRegister::CashRegister()
{
item_count = 0;
total_price = 0;
}
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 52
Constructors
Constructors can have parameters, and constructors can be
overloaded:
class BankAccount
{
public:
// Sets balance to 0
BankAccount();
// Sets balance to initial_balance
BankAccount(double initial_balance);
// Member functions omitted
private:
double balance;
};
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 53
Constructors

BankAccount Ivans_account;
// Uses default BankAccount constructor

BankAccount Elenas_account(499.95);
// Uses BankAccount(double) constructor

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 54


Inheritance - Implementing Derived Classes
The : symbol denotes inheritance.
Derived
class

Parent:
class ChildClass : public ParentClass the base class
{
public:
// New and changed member
// functions will go here
private:
// Additional data members
// will go here
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 55

};
class Animal { is-a relationship
// eat() function Inheritance is an is-a
// sleep() function relationship. We use
}; inheritance only if an is-a
relationship is present
class Dog : public Animal { between the two classes.
// bark() function
}; Here are some examples:

A car is a vehicle.
Orange is a fruit.
A surgeon is a doctor.
A dog is an animal.
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 56
// base class
class Animal {
int main() {
public: // Create object of the Dog class
void eat() { Dog dog1;
cout << "I can eat!" << endl;
}
// Calling members of the base class
void sleep() { dog1.eat();
cout << "I can sleep!" << endl; dog1.sleep();
}
}; // Calling member of the derived class
dog1.bark();
// derived class
class Dog : public Animal { return 0;
}
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
} 57
};
CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++
class Cat : protected Animal {
// code
};
The various ways we can derive classes are known as access modes. These access
modes have the following effect:

public: If a derived class is declared in public mode, then the members of the base
class are inherited by the derived class just as they are.
private: In this case, all the members of the base class become private members in
the derived class.

protected: The public members of the base class become protected members in
the derived class.
***The private members of the base class are always private in the derived class.
58

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++


Derived Classes

The derived class inherits all data members and all


functions of the base class that it does not
override.

Override by re-defining data members and member


functions in derived class.

Chapter 5- Introduction to OOP Programming - C++ 59


Function Overloading and Polymorphism
• Having functions with the same name is called function
overloading

• Polymorphism is what allows functions with the same name


to do different things based on its arguments.

• Polymorphism is available for objects.

CHAPTER 5- INTRODUCTION TO OOP PROGRAMMING - C++ 60

You might also like