0% found this document useful (0 votes)
12 views

Lect 5 - Introduction To Classes and Objects

Introduction to class
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lect 5 - Introduction To Classes and Objects

Introduction to class
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

OBJECT ORIENTED PROGRAMMING

INSTRUCTOR: Ms. Sanneya Aziz


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.
 The "Don't Repeat Yourself" (DRY) principle is about reducing the
repetition of code. You should extract out the codes that are common
for the application, and place them at a single place and reuse them
instead of repeating it.
WHY IS OOP NEEDED?

 OOP makes it easy to maintain and modify existing code as new objects
can be created with small differences to existing ones.
 OOP provides a good framework for code libraries where supplied
software components can be easily adapted and modified by the
programmer.
ADVANTAGES
 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.
 Objects are modelled on real world entities.
 It provides data hiding .
 It provides data encapsulation.
CLASS IN C++
 Class is just a blue print, containing only list of variables and methods
(functions) where no memory is allocated to them.
 A class is a group of objects that has common properties.
 Classes are expanded version of structures.
 Structures can contain only multiple variables.
 Classes can contain multiple variables, classes can also contain functions
as class member
 In other words , they are functions + structures with some differences.
CLASS IN C++
 Encapsulates data(attributes) and functions(behavior) into packages called
classes .
 Class is a place where we can define the properties and functionalities of the
objects.
 Variables declared in class are called data members.
 Functions declared or defined in class are called member functions.
 The instance of class are called object.
 So classes are the user defined (programmer defined) types having
Variables( data members)
Functions ( member functions )
CLASS DECLARATION

 Declaration of class must start with the keyword class followed by the
class name.
 Members of a class are declared within braces.
 A terminator (;) must be inserted after the closing bracket.
class class_name
{
// data members
// member functions
};
EXAMPLE
class Employee
{
private:
char name[25];
int age;
long salary;
public:
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
private:
char name[25];
int age;
long salary; Body of the
public: class
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
Class is a
private:
keyword
char name[25];
int age;
long salary;
public:
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
Class name
private:
char name[25];
int age;
long salary;
public:
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
Starting
private:
class scope
char name[25];
int age;
long salary;
public:
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
Access
private:
specifier
char name[25];
int age;
long salary;
public:
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
private:
char name[25];
int age;
Private data
long salary;
members of
public: class
void getdata();
void putdata();
};
EXAMPLE
class Employee
{
private:
char name[25];
int age;
long salary;
public:
Access
void getdata(); specifier
void putdata();
};
EXAMPLE
class Employee
{
private:
char name[25];
int age;
long salary;
public:
void getdata(); Public member
void putdata(); functions of
}; class
EXAMPLE
class Employee
{
private:
char name[25];
int age;
long salary;
public:
void getdata(); Semicolon
void putdata(); and end of
}; class scope
CLASSES (POINTS TO REMEMBER)
 If a member of a class is a variable, you declare it just like any other variable.
 Also, in C++ versions prior to C++11, in the definition of the class, you
cannot initialize a variable when you declare it.
 If a member of a class is a function, you typically use the function prototype to
declare that member.
 If a member of a class is a function, it can (directly) access any member of the
class—member variables and member functions.
 when you write the definition of a member function, you can directly access any
member variable of the class without passing it as a parameter.
 The only condition is that you must declare an identifier before you can use it.
OBJECTS
 An Object is an identifiable entity with some characteristics and
behavior.
 An Object is an instance of a Class. When a class is defined, no memory
is allocated but when it is instantiated (i.e. an object is created) memory
is allocated.
 Object is identified by its unique name.
 Object take up space in memory and have an associated address like a
record in pascal or structure or union in C.
 When a program is executed the objects interact by sending messages
to one another.
OBJECTS (CONT…)

 Each object contains data and code to manipulate the data.


 Objects can interact without having to know details of each other’s data
or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
 There can be more instance of a class.
 Each instance of a class hold its own relevant data.
EXAMPLE WITH SINGLE INSTANCE
class MyClass // The class
{ public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() Output:
{ 15
MyClass myObj; // Create an object of MyClass Some text
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0; }
Output:
BMW X5 1999
EXAMPLE WITH MULTIPLE INSTANCES Ford Mustang 1969

class Car { Car carObj2; // Create another object of Car


public: carObj2.brand = "Ford";
string brand; carObj2.model = "Mustang";
string model; carObj2.year = 1969;
int year; // Print attribute values
}; cout << carObj1.brand << " " <<
int main() carObj1.model << " " <<
{ carObj1.year << "\n";
Car carObj1;// Create an object of Car cout << carObj2.brand << " " <<
carObj1.brand = "BMW"; carObj2.model << " " <<
carObj1.model = "X5"; carObj2.year << "\n";
carObj1.year = 1999; return 0; }
HEADER FILE
//File: header1.h for(int i=1; i<=number; i++)
class factorial {
{ factorial=factorial*i;
private: }
int number , factorial=1; cout<<"Factorial of Given Number is: "
public: << factorial << endl;
void fact() }
{ };
cout << "Enter Number To Find Its
Factorial: ";
cin>>number;
CPP FILE
//File: main.cpp
#include “header1.h”
#include<iostream>
using namespace std;
int main()
{
factorial f;
f.fact();
system(“pause”);
return 0;
}
WAYS OF DEFINING MEMBER FUNCTIONS OF CLASS

There are two ways in which the member functions can be defined
 Inside the class definition
 Outside the class definition
INSIDE CLASS DEFINITION

 As the name suggests, here the functions are defined inside the class.
 Functions defined inside the class are treated as inline functions
automatically if the function definition doesn’t contain looping
statements or complex multiple line operations.
 You can access methods (functions) just like you access attributes by
creating an object of the class and by using the dot syntax(.).
EXAMPLE
#include <iostream> cin>> car_model;
using namespace std; }
class car void showdata()
{ {
private: cout<<“car number is <<“car_number<<endl;
int car_number ; cin<<“car model is”<<car_model<<endl;
char car_model[10] }};
public: int main()
void getdata() { car c1;
{ c1.getdata();
cout<<“enter car number”<<endl; c1.showdata(); Function definition
cin>> car_number; system(“pause”); inside the class
cout<<“enter car model”<<endl; return 0; }
OUTSIDE CLASS DEFINITION
 As the name suggests, here the functions are defined outside the class
however, they are declared inside the class.
 Functions should be declared inside the class to bound it to the class and
indicate it as it’s member but they can be defined outside of the class.
 To define a function outside of a class, scope resolution operator :: is
used.
 This is done by specifying data type than the name of the class ,
followed the scope resolution :: operator , followed by the name of
the function.
OUTPUT:
Hello World!
EXAMPLE

class MyClass
{ // The class
public: // Access specifier
void myMethod(); // function declaration
};
void MyClass::myMethod() //function definition outside the class
{
cout << "Hello World!";
}
int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
CONSTRUCTOR

 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
parenthesis ().
 The constructor has the same name as the class.
 It is always public and it does not have any return value.
 The constructor that accept no parameters is called default constructor.
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)
sytem (“pause”)
return 0;
}
CONSTRUCTOR WITH 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:
OUTPUT:
BMW X5 1999
EXAMPLE Ford Mustang 1969

class Car // The class // Create Car objects and call the constructor with different values
{ int main()
public: // Access specifier {
string brand; // Attribute Car carObj1("BMW", "X5", 1999);
string model; // Attribute Car carObj2("Ford", "Mustang", 1969);
int year; // Attribute // Print values
// Constructor with parameters cout << carObj1.brand << " " <<
Car(string x, string y, int z) carObj1.model << " " << carObj1.year << "\n";
{ brand = x;
cout << carObj2.brand << " " <<
model = y;
year = z; carObj2.model << " " << carObj2.year << "\n";
} return 0;
}; }
CONSTRUCTOR OUTSIDE THE CLASS

 Just like functions, constructors can also be defined outside the class.
 First, declare the constructor inside the class, and then define it outside
of the class by specifying the name of the class, followed by the scope
resolution :: operator, followed by the name of the constructor (which is
the same as the class):
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
Car::Car(string x, string y, int z) // Constructor definition outside the class
{ 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; }
PRACTICE

 EXAMPLE 10-8, 10-9 from the text book


 All other related examples and exercise Questions.
DESTRUCTOR
 It is a special member of a class , which is used to destroy the memory
of the object.
 Its name is same as the class name but till sign followed by destructor
 It must be declared in public part
 Never it take any arguments nor does it return any value not even void
otherwise result will be error
 It will be invoked implicitly by compiler upon exit from program or a
block or a function
 It is followed by ~ operator, followed by the name of the class
class HelloWorld OUTPUT:
{ Constructor is called Hello
World!
public:
HelloWorld() //Constructor Destructor is called
{
cout<<"Constructor is called"<<endl;
}
~HelloWorld() //Destructor
{
cout<<"Destructor is called"<<endl; }
void display() //Member function
{ cout<<"Hello World!"<<endl; }
};
int main()
{
HelloWorld obj; //Object created
obj.display(); //Member function called
return 0; }
ACCESS SPECIFIER

 Access specifiers define how the members (attributes and methods) of a


class can be accessed.
 There can be three access specifiers in C++
Private
Public
Protected
 Private , public and protected are also known as visibility labels
 In C++, data can be hidden by making it private
PRIVATE
 Private means that no one can access the class members declared private
outside that class
 If someone tries to access the private member, they will get a compile time
error
 When no access specifier mention then default access specifier is private
 Syntax
class privateaccess
{
private: // private access specifier
int x; // data member declaration
void display(); //member function declaration
};
PUBLIC

 Public means that the data members and member functions can be
accessed by other classes too
 If the members are public it means that it can be accessed and
modified outside the class
 Syntax
class Publicaccess
{
public: // public access specifier
int x; // data member declaration
void display(); //member function declaration
};
PROTECTED

 Protected is similar to private


 It makes class member inaccessible outside the class but they can be
accessed by any subclass of that class
 e.g if class A is inherited by class B , then class B is subclass of class A.
 Syntax
class protectedaccess
{
protected : // protected access specifier
int x; // data member declaration
void display(); //member function declaration
};
EXAMPLE
class MyClass
{
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute If you try to access a private
}; member, an error occurs:
int main() Error: y is private
{
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
ACCESS SPECIFIERS IN C++
ACCESS SPECIFIERS IN C++ (CONT…)
ENCAPSULATION

 The meaning of Encapsulation, is to make sure that "sensitive" data is


hidden from users.
 To achieve this, you must declare class variables/attributes
as private (cannot be accessed from outside the class).
 If you want others to read or modify the value of a private member, you
can provide public get and set methods.
ROLE OF ACCESS SPECIFIERS IN ENCAPSULATION

 The process of implementing encapsulation can be sub-divided into two


steps:
 The data members should be labeled as private using the private access
specifiers
 The member function which manipulates the data members should be
labeled as public using the public access specifier
EXAMPLE
class Encapsulation int main()
{ {
private; // data hidden from outside world Encapsulation obj;
int x; obj.set(5);
public: cout<<obj.get();
void set(int a) return 0;
{ // function to set value of variable x }
x =a
In this program the variable x is made
} private. This variable can be accessed and
int get() manipulated only using the functions get()
{ // function to return value of variable x and set() which are present inside the class.
return x; Thus we can say that here, the variable x
and the functions get() and set() are binded
}
together which is nothing but encapsulation.
};

You might also like