GP OOPS C++ Class
GP OOPS C++ Class
Class
A class is a logical entity used to define a new data type. A class is a user-defined type
that describes what a particular kind of object will look like. A class contains
variables(data members), methods, and constructors.
Data encapsulation is supported with “class”. The class consists of both data and
functions. The data in a class is called a member, while functions in the class are called
methods.
Data Members:- The variables which are declared in any class by using any
fundamental data types (like int, char, float, etc.) or derived data types (like class,
structure, pointer, etc.) are known as Data Members.
Constructor:- Constructors are special class functions that perform the initialization of
every object. In C++, the constructor is automatically called when an object is created. It
is a special method of the class because it does not have any return type. It has the
same name as the class itself.
class class_name{
//class body
1
//data_members
//constructor (optional)
//methods
};
Here,
❖ class: class keyword is used to create a class in C++.
❖ class_name: The name of the class.
❖ class body: Curly braces surround the class body.
❖ After closing curly braces, a semicolon(;) is used.
Classes are very useful in programming. Consider the example of where you don't want
to use just one Smartphone but 100 smartphones. Rather than describing each one in
detail from scratch, you can use the same smartphone class to create 100 objects of the
type ‘smartphones’. You still have to give each one a name and other properties, but the
basic structure of what a smartphone looks like is the same.
The smartphone class would allow the programmer to store similar information unique
to each car (different models, maybe different colors, etc.) and associate the
appropriate information with each smartphone.
//Data Members(Properties)
string model;
int year_of_manufacture;
bool _5g_supported;
//Constructor
smartphone(string mod, int manu, bool _5g_supp){
//initialzing data members
model = mod;
year_of_manufacture = manu;
_5g_supported = _5g_supp;
}
//methods
2
void print_details(){
cout << "Model : " << model << endl;
cout << "Year of Manufacture : " << year_of_manufacture << endl;
cout << "5g Supported : " << _5g_supported << endl;
}
};