0% found this document useful (0 votes)
0 views54 pages

PF Lab 10

The document provides an introduction to Object-Oriented Programming (OOP) in C++, covering key concepts such as classes, objects, access specifiers, constructors, destructors, and the principles of encapsulation and abstraction. It explains the differences between classes and structures, outlines various programming paradigms, and details the syntax for declaring classes and methods. Additionally, it includes tasks for practical application of the concepts learned.

Uploaded by

tips&tricks4U
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)
0 views54 pages

PF Lab 10

The document provides an introduction to Object-Oriented Programming (OOP) in C++, covering key concepts such as classes, objects, access specifiers, constructors, destructors, and the principles of encapsulation and abstraction. It explains the differences between classes and structures, outlines various programming paradigms, and details the syntax for declaring classes and methods. Additionally, it includes tasks for practical application of the concepts learned.

Uploaded by

tips&tricks4U
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/ 54

Programming

Fundamentals
in
C++
Object Oriented Programming

Objective: Introduction to Object Oriented Programming, to become familiar


with Objects and classes, declaring a class with variables(member data) and
member functions/methods and Instantiating an object of a class, and become
familiar with:
Member data and Member functions
access specifiers : private, public and protected
set() and get() functions.
Constructor and Destructor.
static (class) variables
Object Oriented Programming

 What is a Programming Paradigm ?

Definition: A programming paradigm is a style


or “way” of programming.
Some of the more common paradigms are:
 Structured — Programs have clean, goto-free, nested control structures.
 Array-based —
 Functional Programming
Object Oriented Programming

Some of the more common paradigms are:


Event-Driven — Control flow is determined by
asynchronous actions (from humans or sensors).
GUI-Based
Programming Paradigm

 Imperative — Control flow is an explicit sequence of commands.

 Procedural — Imperative programming with procedure calls.

 Flow-Driven — Computation is specified by multiple processes


communicating over predefined channels.

 Logic (Rule-based) — Programmer specifies a set of facts and rules,


and an engine infers the answers to questions.
Programming Paradigm

 Constraint — Programmer specifies a set of constraints, and an engine infers the answers to
questions.
 Aspect-Oriented — Programs have cross-cutting concerns applied transparently

 Object-Oriented — Computation is effected by sending messages


to objects; objects have state and behavior.

 Class-based — Objects get their state and behavior based on membership


in a class.
Introduction to Object-Oriented Programming

 Object-Oriented Programming : is a Programming paradigm or a software


development methodology in which a program is conceptualized as a group
of objects .
 A Programming technique in which a program is organized as a collection of
objects.

 A software development approach for writing and developing computer


programs based on objects.
Introduction to Object-Oriented Programming

OOP provides an easy of modeling things in the real


world.
OOP organizes & combines data and functions
together, hides and encapsulates the implementation
details and offers several features for developing
computer softwares.
Introduction to Object-Oriented Programming

 OOP : makes the development process easier faster and less time consuming.

 OOP features :
 Classes and Objects
 Data Encapsulation and Abstraction
 Inheritance

 Polymorphism

 And a programming language that supports or follows these features is called an


Object-Oriented Programming Language.
OOP Classes and Objects

 Two key concepts in OOP are :


 Objects and classes
An object is and entity that has certain
attributes or properties sometimes called
characteristics which may be assigned values.
The values can be numeric or non-numeric.
Introduction to Object-Oriented Programming

 An Analogy
 Examples of real world Objects
 In the real world everywhere we look we see objects such :
Introduction to Object-Oriented Programming

 An object represents a real world entity Students


Object
 Following figure shows some real-world entities
Book object
Introduction to Object-Oriented Programming

Book object
Attributes/
Properties
BookName

AuthorName

Price

Edition
Introduction to Object-Oriented Programming

car object
Attributes

Name

Model

Price

Color
Introduction to Object-Oriented Programming

 Attributes are represented as variables in a class declaration.


Students
Attributes Object

Name

RollNo

Address
Introduction to Object-Oriented Programming

Attributes with values Students


Object

Name=“anyNam
e”

RollNo=19S
w

Address=xy
z
Introduction to Object-Oriented Programming

Attributes with
values car object

Name=Alto

Model=2017

Price=

Color=white
Introduction to Object-Oriented Programming

Attributes
car object
Name
Model
Price
Color

Behavior

Change gear()
Apply breaks()
Accelerate()
Introduction to Object-Oriented Programming

Attributes

Name  Behavior
is equivalent to a
RollNo method in a program
Address

Behavior

setName()
changedept(
);
An Analogy
Classes : A class is a template for an object. Or
Classes are the definitions (or blueprints) Used to created objects.
The structure or
Design of a car
An Analogy

Object 1 Object 2
Coding is flat only in trivial systems.
University

BM CS SW ……….. Examination
Admission Finance

Employees Students
OOP Class and Object

Class: A class is a template for an object. OR


 Classes are the definitions (or blueprints) Used to created objects.
 Object : in general an object is an entity that has certain attributes or properties
which may be assigned values The values can be numeric or non-numeric.
 In OOP an Object is an instance of a class OR
an Object is a working copy of a class OR Look like a class.
 Objects in a program can represent real world things e.g. automobiles, Mobiles,
Books houses and employees.
OOP Class and Object

 There are just two kinds of things that you can include in a class definition:
 Fields: These are variables that store data items .They are also referred to as data members of a
class.

 The data, or variables, defined within a class are called member data

 Methods: These define the operations you can perform for the class —so they determine what you
can do to, or with, objects of the class. Methods typically operate on the fields —the data members
of the class.

 Collectively, the methods and variables defined within a class are called members of the class.
OOP Class and Object

 Syntax
 class classname {
 type variable1;
 type variable2;
 type variableN;
 type methodname1(parameter-list) {
 // body of method
 }
 // ...
 type methodnameN(parameter-list) {
 // body of method
 }

Declaring a class with a method and
Instantiating an object of a class.

A Simple Class Use MyClass Class

class MyClass { int main () {

public : // access specifier // Creating an object of MyClass

void DispayMsg() MyClass MyObj; // Instantiating an object of


{ MyClass
Cout<<“Welcome to Class 19SW-Section-I”;
{
}// end method // calling MyObj’s method DisplayMsg()

} ; // end class MyObj.DisplayMsg();

return 0;

} // end main method


Declaring a class with Variables
Use Students Class
A Simple Class
int main () {
class Students {
// Creating an object and asdign it to objStd
Private:
string student_rollno; // instance
Students objStd;
variable
{
Public:
// calling objStd’s method set_rollno()
void set_rollno(string rollno)
{
objStd. set_rollno(“20SW01");
student_rollno = rollno;
} // end method
// calling objStd’s method get_rollno()
string get_rollno()
/ cout<<“Welcome”+ objStd. get_rollno());
{
return student_rollno;
return 0;
} // end method
} // end main method

} ; // end class
Each object (instance) of a class
contains/maintains it’s own copy
of the class’s instance variables
and functions.
Primitive Types vs. Reference Types
Data types in C++ are divided into two categories
Primitive Types and Reference Types

Primitive Types are byte, int, char, Boolean, short, long, float and double.

A primitive variable can store exactly one value of its declared type at a
time.
Reference Types

All non primitive types are references types, so classes, we specify


the types of objects are reference types.

Variables of reference types (normally called references)


store the locations of objects in the computer’s memory.
Such variables are said to refer to objects in the program.
OOP set() & get() methods

(Set methods) & (get methods)


These are the public member functions methods.
Allow the client of the class to set(i.e. assign values)
to the private instance variables , and
get (i.e. obtain values) of private instance variables.
OOP Access Specifiers

 Access Specifiers : Define level of Accessibility of a variable or a method OR


 Specify which part of the program can access a variable or a function.
 Private : variables or methods declared with access specifier private are
accessible only within a class in which they are declared.

 Public : variables or methods declared with access specifier public are


accessible anywhere in the program (i.e. within a class in which they are
declared and also outside that class)
Protected : variables or methods declared with access specifier protected
are accessible within a class in which they are declared and also in the derived
class).
Introduction to Object-Oriented Programming

 Data Encapsulation & Abstraction


 Data Encapsulation or data hiding: Is an OOP feature that binds together data and
functions. OR
 The wrapping of data and functions into a single unit. OR
 The internal of the object is private to that object and may not be accessed from
outside the object

 Abstraction: refers to the act of representing the functionality of a program and hide
the internal details. OR
 A feature of OOP where by the implementation details of class are kept
hidden from the user.
Data Encapsulation & Abstraction
OOP Constructor

 A Constructor : is a special member function which is called


automatically whenever an object of class is created.
 When an object of class is created, the constructor of that class is called.
 Is used to Initialize an object, and to initialize the instance variables.
 A constructor has two special characteristics that differentiate it from
other class methods:
 A constructor always has the same name as the class
 A constructor never returns a value, and you must not specify a return
type —not even of type void.
A Simple Class with Constructor

class Students {
private: int main () {
string studentName; // instance variable
// Creating an object
public:
Students () //Constructor Students objStd;
{
studentdName=“anyName”) ; } {
// calling objStd’s method getName()
void setName(String stdName) cout<<“Initial Value:”+ objStd.getName());
{
studentName=stdName; objStd.setName(“Ahmed");
} // end method cout<<“Welcome”+ objStd.getName());
public String getName() return 0;
{
return studentName; } // end main method
} // end method

}; // end class
OOP Constructors

 No-argument constructor initializes data members to constant values,

 A multi-argument constructor can initialize data members to values


passed as arguments,

 A default copy constructor initializes an object with an other object of


the same type.
 This is one argument constructor whose argument is an object of the
same class as the constructor.
Static class variables

 Each object (instance) of a class contains/maintains it’s


own copy of the class’s instance variables.

 Static instance variables are not duplicated for each


object, rather a single data item (i.e. static member is
shared by all objects of a class)
OOP Destructor

 Destructor : Is a member function which is called automatically


whenever an object is destroyed.

 It has the same name as the constructor (which is the same as the class
name) but is preceded by a Tilde ~ .
 The most common use of destructor is to deallocate the memory that
was allocate by the constructor for the object.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its
class members when the object is destroyed. A destructor is called for a class object when that
object passes out of scope or is explicitly deleted.

If you do not define a destructor, the compiler will provide a default one; for many classes

If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares
a destructor. This implicitly declared destructor is an inline public member of its class.
The compiler will implicitly define an implicitly declared destructor when the compiler uses the
destructor to destroy an object of the destructor's class type
 When does the destructor get called?
A destructor is a member function that is invoked automatically
when the object goes out of scope or is explicitly destroyed by a call
to delete
The program finished execution.
2) When a scope (the { } parenthesis) containing local variable
ends.
3) When you call the delete operator.
#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor HelloWorld(){
cout<<"Constructor is Output:
called"<<endl; } Constructor is called
Hello World!
//Destructor
Destructor is called
~HelloWorld(){
cout<<"Destructor is
called"<<endl; }

//Member function

void display(){ cout<<"Hello


World!"<<endl;
} };
int main(){
//Object created
HelloWorld obj;
//Member function called obj.display();
Structures and Classes

 Structures are the important building blocks in understanding of


Objects and classes. You can use structures in almost exactly
the same way that you use classes.
 The difference between class and struct are:
 A structure is collection of data, while a class is collection of
both data and functions.
 In a class the members are private by default, while in a
structure they are public by default.
 Classes are reference types, while structures are values types.
 http://www.differencebetween.info/difference-between-
class-and-structure-in-cplusplus
Difference between Class and
Structure

Class Structure
Classes are of reference types. Structs are of value types.
All the reference types are allocated on heap memory. All the value types are allocated on stack memory.
Allocation of large reference type is cheaper than Allocation and de-allocation is cheaper in value type as compare to
allocation of large value type. reference type.
Class has limitless features. Struct has limited features.
Class is generally used in large programs. Struct are used in small programs.
Structure does not contain parameter less constructor or destructor,
Classes can contain constructor or destructor.
but can contain Parameterized constructor or static constructor.
Classes used new keyword for creating instances. Struct can create an instance, with or without new keyword.
A Class can inherit from another class. A Struct is not allowed to inherit from another struct or class.
The data member of a class can be protected. The data member of struct can’t be protected.
Function member of the class can be virtual or abstract. Function member of the struct cannot be virtual or abstract.
Two variable of class can contain the reference of the Each variable in struct contains its own copy of data(except in ref
same object and any operation on one variable can affect and out parameter variable) and any operation on one variable can
another variable. not effect another variable.
Tasks for Lab # 10
Task # 1 Create a class having 4 functions, add, sub, muland div. Each function accepts 2 parameters
and returns the sum, difference, multiplication and division of these numbers
Create a main () function that uses the above class.

Task # 2
Create a class called MyClass that has one int member. Include member functions to initialize it to 0, to
initialize it to an integer value, to display it.
Write a program to test this class.

Task # 3 Create an employee class. The member should comprise an int for storing the employee
number, and float for the employee’s salary. Member functions should allow the user to enter this data
and display it. Write a main() function that allows the user to enter data for three employees and display
it.

Task # 4 Create a class that includes a data member that holds a “Serial number” for each object
created from the class. That is, the first object created will be numbered 1, the second 2, and so on.

Task # 5 Demonstrate the use of the following:


Constructor
Access specifiers private and public.
Set() and ge() functions.
Tasks for Lab # 10
Develop the Student Registration System by the object oriented scenarios. It should consist of
two classes namely Student, and Course.

using OOP to write a C++ Program to Store Information of a Student in a class

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy