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

Unit-5.1 Notes, Fin

unit 5 notes OOSD

Uploaded by

sumit
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)
24 views

Unit-5.1 Notes, Fin

unit 5 notes OOSD

Uploaded by

sumit
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/ 15

UNIT-5

OBJECTS AND CLASSES


Class: A class in C++ is the building block, that leads to Object-Oriented
programming.
It is a user-de ned data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.

A C++ class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with di erent
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class
and wheels, speed limits, mileage are their properties.
• A Class is a user de ned data-type which has data members and member
functions.

• Data members are the data variables and member functions are the functions
used to manipulate these variables and together these data members and
member functions de nes the properties and behavior of the objects in a
Class.

• In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can be apply brakes, increase speed etc.

An Object is an instance of a Class. When a class is de ned, no memory is


allocated but when it is instantiated (i.e. an object is created) memory is allocated.

• De ning Class and Declaring Objects


• A class is de ned in C++ using keyword class followed by the name of class.
The body of class is de ned inside the curly brackets and terminated by a
semicolon at the end.
fi
fi
fi
fi
fi
fi
fi
ff
• Declaring Objects: When a class is de ned, only the speci cation for the
object is de ned; no memory or storage is allocated. To use the data and
access functions de ned in the class, you need to create objects.

• Syntax:
• ClassName ObjectName;

• Accessing data members and member functions: The data members and
member functions of class can be accessed using the dot(‘.’) operator with the
object.
• For example if the name of object is obj and you want to access the member
function with the name printName() then you will have to write:
• obj.printName() .

• Accessing Data Members
• The public data members are also accessed in the same way given however
the private data members are not allowed to be accessed directly by the
object.

• Accessing a data member depends solely on the access control of that data
member.

• This access control is given by Access modi ers in C++. There are three
access modi ers : public, private and protected.

• EXAMPLE:
• #include <iostream.h>
• using namespace std;
• class student
• {
• // Access speci er
• public:

• // Data Members
• string stuname;

• // Member Functions()
• void printname()
• {
• cout << “student name is: " << stuname;
• }
• };

• int main() {

fi
fi
fi
fi
fi
fi
fi
• // Declare an object of class geeks
• Student obj1;

• // accessing data member
• obj1.stuname = "Abhi";

• // accessing member function
• obj1.printname();
• return 0;
• }

• Member Functions in Classes


• There are 2 ways to de ne a member function:
‣ 1. Inside class de nition
‣ 2. Outside class de nition

• To de ne a member function outside the class de nition we have to use the
scope resolution :: operator along with class name and function name
• #include <bits/stdc++.h>
• using namespace std;
• class student
• {
• public:
• string stuname;
• int id;

• // printname is not de ned inside class de nition
• void printname();

• // printid is de ned inside class de nition
• void printid()
• {
• cout << "student id is: " << id;
• }
• };

• // De nition of printname using scope resolution operator ::
• void student::printname()
• {
• cout << “Student name is: " << stuname;
• }
• int main() {

• Student obj1;
• obj1.stuname = "xyz";
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
• obj1.id=15;

• // call printname()
• obj1.printname();
• cout << endl;

• // call printid()
• obj1.printid();
• return 0;
• }
• Output:
• Student name is: xyz
• Student id is: 15

Public and private members


• Access modi ers are used to implement an important aspect of Object-
Oriented Programming known as Data Hiding.
• Access Modi ers or Access Speci ers in a class are used to assign the
accessibility to the class members. That is, it sets some restrictions on the
class members not to get directly accessed by the outside functions.
There are 3 types of access modi ers available in C++:
• 1. Public
• 2. Private
• 3. Protected

• 1. Public: All the class members declared under the public speci er will be
available to everyone. The data members and member functions declared as
public can be accessed by other classes and functions too. The public
members of a class can be accessed from anywhere in the program using the
direct member access operator (.) with the object of that class.
• #include<iostream>
• using namespace std;

• // class de nition
• class Circle
• {
• public:
• double radius;

• double compute_area()
• {
• return 3.14*radius*radius;
• }

• };
fi
fi
fi
fi
fi
fi

• // main function
• int main()
• {
• Circle obj;

• // accessing public datamember outside class
• obj.radius = 5.5;

• cout << "Radius is: " << obj.radius << "\n";
• cout << "Area is: " << obj.compute_area();
• return 0;
• }
• Output:
• Radius is: 5.5
• Area is: 94.985

• 2. Private: The class members declared as private can be accessed only by
the member functions inside the class. They are not allowed to be accessed
directly by any object or function outside the class. Only the member
functions or the friend functions are allowed to access the private data
members of a class.
• Example:
• #include<iostream>
• using namespace std;

• class Circle
• {
• // private data member
• private:
• double radius;

• // public member function
• public:
• void compute_area(double r)
• { // member function can access private
• // data member radius
• radius = r;

• double area = 3.14*radius*radius;

• cout << "Radius is: " << radius << endl;
• cout << "Area is: " << area;
• }

• };

• // main function
• int main()
• {
• // creating object of the class
• Circle obj;

• // trying to access private data member
• // directly outside the class
• obj.compute_area(1.5);


• return 0;
• }
• Output:
• Radius is: 1.5
• Area is: 7.065

• 3. Protected: Protected access modi er is similar to private access modi er
in the sense that it can’t be accessed outside of it’s class unless with the help
of friend class, the di erence is that the class members declared as Protected
can be accessed by any subclass(derived class) of that class as well.
• Note: This access through inheritance can alter the access modi er of the
elements of base class in derived class depending on the modes of
Inheritance.
• Example:
• #include <bits/stdc++.h>
• using namespace std;

• // base class
• class Parent
• {
• // protected data members
• protected:
• int id_protected;

• };

• // sub class or derived class from public base class
• class Child : public Parent
• {
• public:
• void setId(int id)
• {
ff
fi
fi
fi

• // Child class is able to access the inherited
• // protected data members of base class

• id_protected = id;

• }

• void displayId()
• {
• cout << "id_protected is: " << id_protected << endl;
• }
• };

• // main function
• int main() {

• Child obj1;

• // member function of the derived class can
• // access the protected data members of the base class

• obj1.setId(81);
• obj1.displayId();
• return 0;
• }

• Output:
• id_protected is: 81

Static data and function members


• Static Variables : Variables in a function, Variables in a class
Static Members of Class : Class objects and Functions in a class
• Static data members are class members that are declared using static
keywords. A static member has certain special characteristics. These are:

• Only one copy of that member is created for the entire class and is shared by all
the objects of that class, no matter how many objects are created.
• It is initialized before any object of this class is being created, even before main
starts.
• It is visible only within the class, but its lifetime is the entire program.
SYNTAX: static data_type data_member_name;

• Static Variables: Static variables in a Function: When a variable is declared as
static, space for it gets allocated for the lifetime of the program. Even if the
function is called multiple times, space for the static variable is allocated only
once and the value of variable in the previous call gets carried through the
next function call.

• EXAMPLE:
• #include <iostream>
• #include <string>
• using namespace std;

• void demo()
• {
• // static variable
• static int count = 0;
• cout << count << " ";

• // value is updated and
• // will be carried to next
• // function calls
• count++;
• }

• int main()
• {
• for (int i=0; i<5; i++)
• demo();
• return 0;
• }
• OUTPUT: 0 1 2 3 4

• Static variables in a class: As the variables declared as static are initialized


only once as they are allocated space in separate static storage so, the static
variables in a class are shared by the objects. There can not be multiple
copies of same static variables for di erent objects. Also because of this
reason static variables can not be initialized using constructors.

• EXAMPLE:

• #include<iostream>
• using namespace std;

• class GfG
• {
• public:
ff
• static int i;

• GfG()
• {
• // Do nothing
• };
• };

• int GfG::i = 1;

• int main()
• {
• GfG obj;
• // prints value of i
• cout << obj.i;
• }
• OUTPUT: 1

• Static functions in a class: Just like the static data members or static
variables inside the class, static member functions also does not depend on
object of class.
• We are allowed to invoke a static member function using the object and the ‘.’
operator but it is recommended to invoke the static members using the class
name and the scope resolution operator.
Static member functions are allowed to access only the static data members
or other static member functions, they can not access the non-static data
members or member functions of the class.

CONSTRUCTORS

A constructor is a special type of member function of a class which initializes
objects of a class.
• In C++, Constructor is automatically called when object(instance of class)
create.
• It is special member function of the class with the same name as that of class
and it does not have any return type.

• A constructor is di erent from normal functions in following ways:
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• It must be placed in public section of class.
ff
• If we do not specify a constructor, C++ compiler generates a default constructor
for object (expects no parameters and has an empty body).

• Default Constructors: Default constructor is the constructor which doesn’t


take any argument. It has no parameters.
• Example:

• #include <iostream>
• using namespace std;

• class construct
• {
• public:
• int a, b;

• // Default Constructor
• construct()
• {
• a = 10;
• b = 20;
• }
• };

• int main()
• {
• // Default constructor called automatically
• // when the object is created
• construct c;
• cout << "a: " << c.a << endl
• << "b: " << c.b;
• return 1;
• }
• Output:
• a: 10
• b: 20
• Even if we do not de ne any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.

• 2. Parameterized Constructors: It is possible to pass arguments to
constructors. Typically, these arguments help initialize an object when it is
created. To create a parameterized constructor, simply add parameters to it
the way you would to any other function. When you de ne the constructor’s
body, use the parameters to initialize the object.

• #include <iostream>
• using namespace std;

• class Point
• {
• private:
• int x, y;

• public:
• // Parameterized Constructor
• Point(int x1, int y1)
• {
• x = x1;
• y = y1;
• }

• int getX()
• {
• return x;
• }
• int getY()
• {
• return y;
• }
• };

• int main()
• {
• // Constructor called
• Point p1(10, 15);

• // Access values assigned by constructor
• cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

• return 0;
fi
fi
• }
• Output:
• p1.x = 10, p1.y = 15
• When an object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function. The normal way
of object declaration may not work. The constructors can be called explicitly
or implicitly.
• Uses of Parameterized constructor:
• It is used to initialize the various data elements of di erent objects with
di erent values when they are created.
• It is used to overload constructors.

• 3. Copy Constructor: A copy constructor is a member function which
initializes an object using another object of the same class.
• A copy constructor is a member function that initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
• ClassName (const ClassName &old_obj);

• EXAMPLE:
• #include<iostream>
• using namespace std;

• class Point
• {
• private:
• int x, y;
• public:
• Point(int x1, int y1) { x = x1; y = y1; }

• // Copy constructor
• Point(const Point &p1) {x = p1.x; y = p1.y; }

• int getX() { return x; }
• int getY() { return y; }
• };

• int main()
• {
• Point p1(10, 15); // Normal constructor is called here
• Point p2 = p1; // Copy constructor is called here

• // Let us access values assigned by constructors
• cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
• cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
ff
ff

• return 0;
• }
• Output:
• p1.x = 10, p1.y = 15
• p2.x = 10, p2.y = 15

• When is copy constructor called?
In C++, a Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
It is, however, not guaranteed that a copy constructor will be called in all these
cases, because the C++ Standard allows the compiler to optimize the copy
away in certain cases, one example is the return value optimization
(sometimes referred to as RVO).

• When is a user-de ned copy constructor needed?
If we don’t de ne our own copy constructor, the C++ compiler creates a
default copy constructor for each class which does a member-wise copy
between objects. The compiler created copy constructor works ne in general.
We need to de ne our own copy constructor only if an object has pointers or
any runtime allocation of the resource like lehandle, a network
connection..etc.
The default constructor does only shallow
copy.


• Deep copy is possible only with user de ned
copy constructor. In user de ned copy
constructor, we make sure that pointers (or
references) of copied object point to new
memory locations.


fi
fi
fi
fi
fi
fi
fi
• DESTRUCTORS
• What is a destructor?
Destructor is an instance member function which is invoked automatically
whenever an object is going to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is destroyed.

• Syntax:
• ~constructor-name();

• Properties of Destructor:
• 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

• How are destructors di erent from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

EXAMPLE:
• class String {
• private:
• char* s;
• int size;

• public:
• String(char*); // constructor
• ~String(); // destructor
• };

• String::String(char* c)
• {
• size = strlen(c);
ff
• s = new char[size + 1];
• strcpy(s, c);
• }
• String::~String() { delete[] s; }

You might also like