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

Oops

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, focusing on classes and objects, access specifiers, member functions, friend functions, constructors, destructors, and function overloading. It explains how classes serve as blueprints for objects, encapsulating data and behaviors, and details the syntax and usage of various features including inline functions and constructor overloading. Examples illustrate the implementation of these concepts in C++ programming.

Uploaded by

Lipasa Mundha
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)
11 views

Oops

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, focusing on classes and objects, access specifiers, member functions, friend functions, constructors, destructors, and function overloading. It explains how classes serve as blueprints for objects, encapsulating data and behaviors, and details the syntax and usage of various features including inline functions and constructor overloading. Examples illustrate the implementation of these concepts in C++ programming.

Uploaded by

Lipasa Mundha
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/ 43

OOPS using C++

Classes and Objects


• Class is a blueprint, template, or prototype that defines and describes
the static attributes and dynamic behaviors common to all objects of
the same kind.
• Thus, a class is a logical abstraction, but an object has physical
existence. In other words, an object is an instance of a class.
• A class declaration is similar syntactically to a structure.
• The entire general form of a class is:
class class-name {
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ...
access-specifier:
data and functions
} object-list;
Cont’d
• The object-list is optional. If present, it declares objects of the
class. Here, access-specifier is one of these three C++ keywords:
– public
– private
– Protected
• By default, functions and data declared within a class are private
to that class and may be accessed only by other members of the
class.
• The public access specifier allows functions or data to be
accessible to other parts of your program. The protected access
specifier is needed only when inheritance is involved
Cont’d
• A class can be visualized as a three-compartment box:
• Classname (or identifier): identifies the class.
• Data Members or Variables (or attributes, states, fields):
contains the static attributes of the class.
• Member Functions (or methods, behaviors, operations):
contains the dynamic operations of the class.
• In other words, a class encapsulates the static attributes (data)
and dynamic behaviors (operations that operate on the data) in a
box.
• Class Members: The data members and member functions are
collectively called class members.
Example (UML notation)
Class definition
class Circle { // classname
private:
double radius; // Data members (variables)
string color;
public:
double getRadius(); // Member functions
double getArea();
}
Objects
• Objects are the instances of a class.
• All the instances of a class have similar properties, as described in
the class definition. For example, you can define a class called
"Student" and create three instances of the class "Student" for
"Peter", "Paul" and "Pauline".
Cont’d
• Objects are the variables of type class and can be declared as
follows:
Class_name var_name;
• Example:
Student ABC, XYZ;
• Memory space is allocated separately to each object for their
data members. Member variables store different values for
different objects of a class.
Accessing Class members

• Using . (dot) operator.


• Example:
class xyz
{
Int x;
Int y;
public:
int z;
};
---------
----------
xyz p;
p. x =0; error . x is private
p. z=10; ok ,z is public
Cont’d (summary)
• A class is a programmer-defined, abstract, self-contained,
reusable software entity that mimics a real-world thing.
• A class is a 3-compartment box containing the name, data
members (variables) and the member functions.
• A class encapsulates the data structures (in data members) and
algorithms (member functions). The values of the data members
constitute its state. The member functions constitute its
behaviors.
• An instance is an instantiation (or realization) of a particular item
of a class.
Member function definition
• In C++, the member functions can be coded in two ways :
– Inside class definition
– Outside class definition using scope resolution operator (::)
1. Inside Class Declaration

• When a member function is defined inside a class, we do not


require to place a membership label along with the function
name. We use only small functions inside the class definition and
such functions are known as inline functions.
2. Outside Class Declaration
• In this case, the function’s full name is written as shown:
Name_of_the_class :: function_name
• The syntax for a member function definition outside the class
definition is :
return_type name_of_the_class::function_name (argument list)
{
body of function
}
Friend Functions
• It is possible to grant a nonmember function access to the
private members of a class by using a friend.
• A friend function has access to all private and protected
members of the class for which it is a friend.
• To declare a friend function, include its prototype within the
class, preceding it with the keyword friend.
• There are two important restrictions that apply to friend
functions. First, a derived class does not inherit friend functions.
Second, friend functions may not have a storage-class specifier.
That is, they may not be declared as static or extern.
#include <iostream>
using namespace std;
class myclass {
Example
int a, b;
public:
friend int sum(myclass x);
void set_ab(int i, int j);
};
void myclass::set_ab(int i, int j) //outside class definition
{ a = i;
b = j;
}
int sum(myclass x) // Note: sum() is not a member function of any class.
{ /* Because sum() is a friend of myclass, it can directly access a and b. */
return x.a + x.b;
}
int main()
{ myclass n;
n.set_ab(3, 4);
cout << sum(n);
return 0;
}
Friend classes

• It is possible for one class to be a friend of another class. When


this is the case, the friend class and all of its member functions
have access to the private members defined within the other
class.
Example #include <iostream>
using namespace std;
class TwoValues {
int a;
int b;
public:
TwoValues(int i, int j) { a = i; b = j; }
friend class Min;
};
class Min {
public:
int min(TwoValues x);
};
int Min::min(TwoValues x)
{ return x.a < x.b ? x.a : x.b; }
int main()
{
TwoValues ob(10, 20);
Min m;
cout << m.min(ob);
return 0;
}
Inline functions
• These are the functions designed to speed up program
execution.
• An inline function is expanded (i.e. the function code is replaced
when a call to the inline function is made) in the line where it is
invoked.
• Syntax:
inline function_header
{
body of the function
}
Example
#include <iostream>
using namespace std;
inline int max(int a, int b)
{
return a>b ? a : b;
}
int main()
{
cout << max(10, 20);
cout << " " << max(99, 88);
return 0;
}
Cont’d
• In this program, the function max() is expanded in line instead of
called.
• As far as the compiler is concerned, the preceding program is
equivalent to this one:
#include <iostream>
using namespace std;
int main()
{
cout << (10>20 ? 10 : 20); //expanded form
cout << " " << (99>88 ? 99 : 88);
return 0;
}
Cont’d
• The reason that inline functions are an important addition to C++
is that they allow you to create very efficient code. It reduces
execution time and helps in faster run times.
• But, it can also result in larger code size because of duplicated
code. For this reason, it is best to inline only very small functions.
• Inline functions may be class member functions.
#include <iostream>
using namespace std;
class myclass {
Example
int a, b;
public:
void init(int i, int j);
void show();
};
inline void myclass::init(int i, int j) //Create an inline function.
{ a = i;
b = j; }

inline void myclass::show() // Create another inline function.


{ cout << a << " " << b << "\n"; }
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Defining Inline functions within class
• When a function is defined inside a class declaration, it is
automatically made into an inline function (if possible). It is not
necessary (but not an error) to precede its declaration with the
inline keyword.
Example
#include <iostream>
using namespace std;
class myclass {
int a, b;
public:
// automatic inline
void init(int i, int j) { a=i; b=j; }
void show() { cout << a << " " << b << "\n"; }
};
int main()
{
myclass x;
x.init(10, 20);
x.show();
return 0;
}
Function overloading
• One way that C++ achieves polymorphism is through the use of
function overloading.
• In C++, two or more functions can share the same name as long
as their parameter declarations are different.
• In this situation, the functions that share the same name are said
to be overloaded, and the process is referred to as function
overloading.
#include <iostream> Example
using namespace std;
// abs is overloaded in 2 ways
int abs(int i);
double abs(double d);
int main()
{
cout << abs(-10) << "\n";
cout << abs(-11.0) << "\n";
return 0;
}
int abs(int i)
{
cout << "Using integer abs()\n";
return i<0 ? -i : i;
}
double abs(double d)
{
cout << "Using double abs()\n";
return d<0.0 ? -d : d;
}
Finding the Address of an Overloaded
Function
• First consider this statement, which assigns the address of some
function called myfunc() to a pointer called p:
p = myfunc;
• If myfunc() is not overloaded, there is one and only one function
called myfunc(), and the compiler has no difficulty assigning its
address to p.
• However, if myfunc() is overloaded, how does the compiler know
which version's address to assign to p? The answer is that it
depends upon how p is declared.
Example
#include <iostream>
using namespace std;
int myfunc(int a);
int myfunc(int a, int b);
int main()
{
int (*fp)(int a); // pointer to int f(int)
fp = myfunc; // points to myfunc(int)
cout << fp(5);
return 0;
}
int myfunc(int a)
{
return a;
}
int myfunc(int a, int b)
{
return a*b;
}
Cont’d
• Here, there are two versions of myfunc() . Both return int, but one
takes a single integer argument; the other requires two integer
arguments.
• In the program, fp is declared as a pointer to a function that returns
an integer and that takes one integer argument. When fp is assigned
the address of myfunc() , C++ uses this information to select the
myfunc(int a) version of myfunc().
• If fp is declared like this:
int (*fp)(int a, int b);
• then fp would have been assigned the address of the myfunc(int a,
int b) version of myfunc().
Constructors
• A constructor is a special function that is a member of a class and has
name same as the class name.
• A constructor is used to construct and initialize all the data
members. To create a new instance of a class, you need to declare
the name of the instance and invoke the constructor.
• For example, we write a constructor for Circle class as:
// Constructor has the same name as the class
Circle(double r = 1.0, string c = "red") {
radius = r;
color = c;
}
• We can create objects as shown below:
• Circle c1(1.2, "blue");
• Circle c2(3.4); // default color
• Circle c3; // default radius and color. note that there is no empty
bracket ()
Cont’d
• In C++, constructor functions cannot return values and, thus, have
no return type.
• An object's constructor is automatically called when the object is
created. This means that it is called when the object's declaration
is executed.
• It is called constructor because it construct the values of data
members of the class.
How constructor is different?
• A constructor function is different from an ordinary function in
the following aspects:
– The name of the constructor is the same as the class name.
– Constructor has no return type (or implicitly returns void).
Hence, no return statement is allowed inside the constructor's
body.
– Constructor can only be invoked once to initialize the instance
constructed. You cannot call the constructor afterwards in
your program.
– Constructors are not inherited.
– If we do not specify a constructor, C++ compiler generates a
default constructor for us (expects no parameters and has an
empty body).
Constructor categories
Default Constructor
• A constructor which has no argument is known as default
constructor. It is invoked at the time of creating object.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;

}
};
int main(void)
{
Employee e1; //creating an object of Employee
Output:
Employee e2;
Default Constructor Invoked
return 0;
Default Constructor Invoked
}
Parameterized Constructor
• It is possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created.
• It is used to provide different values to distinct objects.
• It is used to overload constructors.
#include <iostream>
using namespace std;
Example
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
Employee(int i, string n) //parameterized constructor
{
id = i;
name = n;
}
void display()
{ cout<<id<<" "<<name<<endl; }
};
int main(void) {
Employee e1 =Employee(101, "Sonoo"); //creating an object of Employee
Employee e2=Employee(102, "Nakul");
e1.display();
e2.display();
return 0;
}
Destructors
• A destructor works opposite to constructor; it destructs the
objects of classes. It can be defined only once in a class. Like
constructors, it is invoked automatically.
• A destructor is defined like constructor. It must have same name
as class. But it is prefixed with a tilde sign (~).
• Syntax:
~constructor-name();
Properties of Destructors
• Destructor function is automatically invoked when the objects are
destroyed.
• It cannot be declared static or const.
• The destructor does not have arguments.
• It has no return type not even void.
• An object of a class with a Destructor cannot become a member of
the union.
• A destructor should be declared in the public section of the class.
• The programmer cannot access the address of destructor.
When is destructor called?

• A destructor function is called automatically when the object goes


out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
Example
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
} Output:
~Employee() Constructor Invoked
{ Constructor Invoked
cout<<"Destructor Invoked"<<endl; Destructor Invoked
} Destructor Invoked
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Constructor overloading
• In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments. This
concept is known as Constructor Overloading.
• A constructor is called depending upon the number and type of
arguments passed.
#include <iostream>
using namespace std; Example
class construct
{
public:
float area;
construct() //default constructor
{ area = 0;
}
construct(int a, int b) // // Constructor with two parameters
{ area = a * b;
}
void disp()
{ cout<< area<< endl;
}
};
int main()
{
construct o; //call constructor depending on arguments passed
construct o2( 10, 20);
o.disp();
o2.disp(); Output:
return 1; 0
} 200

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