Objects and Classes
Objects and Classes
Class: A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined 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 different 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 defined 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 defines 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 defined, no memory is allocated but when it is instantiated (i.e.
an object is created) memory is allocated.
Classes in C++
Within the body, the keywords private: and public: specify the access level
of the members of the class.
the default is private.
Usually, the data members of a class are declared in the private: section
of the class and the member functions are in public: section.
Don’t confuse data hiding with the security techniques used to protect
computer databases
Classes in C++
class class_name
{
private: private members or
… methods
…
…
public:
… Public members or
… methods
…
};
Lets start…………
Demonstrates a small, simple object
#include <iostream>
class smallobj
{
private:
int somedata; Data members
public: Output of the
void setdata(int d) Program:
{ somedata = d; Member Functions
} Data is : 1106
void showdata() Data is : 1425
{ cout << "Data is : " << somedata << endl;
}};
int main()
{ smallobj s1, s2;
s1.setdata(1106);
s2.setdata(1425);
s1.showdata(); Calling Member Functions
s2.showdata();
return 0;
}
Classes and Objects
class Book
{
private:
char title[20];
float price;
public:
void getdata(){…..}
void putdata(){…..}
};
int main(){
Book book1,book2,book3;
book1.getdata();
book2.getdata();
….
book1.putdata();
book2.pudata();
….
}
Functions are public, Data is private
Usually the data within a class is private and functions are public
Data is hidden so it will be safe from accidental manipulation
Functions that operate on the data are public so they can be accessed
from outside the class
However, there is no rule that says data must be private and functions
must be public
Objects
1106 1425
void showpart()
{
cout << "Model: " << modelnumber << endl;
cout << "Part: " << partnumber << endl;
cout << "Cost: " << cost << endl;
}
};