Classes and Objects in C++
Classes and Objects in C++
PREPARED BY
Dr.C.MAHIBA
ASSISTANT PROFESSOR/CSBS
2 Classes and Objects
A class in C++ serves as a foundational element for object-
oriented programming.
A Class is like a blueprint and objects are like houses built
from the blueprint
Object Oriented Programming
A class in C++ serves as a foundational element for
object-oriented programming.
User-Defined Data Type: A class is a user-defined
data type in C++. It allows programmers to
encapsulate data and behaviors into a single unit.
Blueprint for Objects: Think of a class as a
blueprint. When you create an object, you’re
essentially creating an instance of that blueprint,
inheriting its attributes and behaviors.
Contains Data and Functions: Within a class, you can
define both data members (variables) and member
functions (methods). These methods define the operations
that can be performed on the data.
Access Control: The members of a class have their access
controlled, ensuring that they can be accessed, modified,
or used based on specified permissions.
A class provides structure and organization to code,
enabling the creation of objects with defined properties
and behaviors.
Classes in C++
A class definition begins with the keyword class.
The body of the class is contained within a set of braces, {
} ; (notice the semi-colon).
class class_name
{
private: private members or
… methods
…
…
public:
… Public members or methods
…
…
};
Classes in C++
Member access specifiers
public:
can be accessed outside the class directly.
The public stuff is the interface.
private:
Accessible only to member functions of class
Private members and methods are for internal use
only.
Class Example
This class example shows how we can encapsulate (gather) a circle
information into one package (unit or class)
#include <iostream>
using namespace std;
class Phone {
public:
double cost;
int slots;
};
int main() {
Phone Y6;
Phone Y7;
Y6.cost = 100.0;
Y6.slots = 2;
Y7.cost = 200.0;
Y7.slots = 2;
cout << "Cost of Huawei Y6 : " << Y6.cost << endl;
cout << "Cost of Huawei Y7 : " << Y7.cost << endl;
cout << "Number of card slots for Huawei Y6 : " << Y6.slots << endl;
cout << "Number of card slots for Huawei Y7 : " << Y7.slots << endl;
return 0;
}
OUTPUT