In this article we will try to understand basic concepts of Object Oriented Programming with C++. Here i will explain the basic concept of Object Oriented Programming for beginners in very simple words with examples in c++. I will be discussing:
1. Class
2. Data Members
3. Members Functions
4. Object
5. Constructor
1. Class
A class is a collection of method and variables. It is a blueprint that defines the data and behavior of a type.
Classes do not set aside storage or define variables. They only tell the compiler what a class looks like.
These are also called programmer-defined types. It is a data type defined by the programmer.
Defining class in C++
class <className> {
};
Example:
Class House{
};
2. Data members and Functions
Each class contains data and functions to manipulate the data. Data components of a class are called data members. Function are called member functions or methods of the class.
In simple words, the variables that you define in a class are called its data members or properties and the functions that you define in the class are called its member functions or methods.
class <className>
{
public:
// Data Members
private:
// Member Functions
};
Example:
class box
{
public:
int height;
int width;
private:
void getValues(int,int);
int area();
};
3. Object
Object is an instance of a class.
Suppose that you have a class “animal”.
You have a cat and your cat is an instance/object of class animal.
When you say, Animal, Cat or Dog, you just mean a kind, your cat, your friend’s cat, and dog.
They are the forms of this class. They have a physical existence while a class is just a logical definition. They are the objects.
While making an object of a class in C++, use the same name of that class and give any name to your objet:
<className> <objectName>;
Animal obj;
4. Constructor
lt is a special member function visible to the user that has the same name as the class.
It has no return type nor “void”.
It is called when an object is declared and is used to set up the object initially. Only called once during initialization.
You can have more than one constructor but each must have unique parameters.
Object Oriented Languages allow classes to have zero, one or more than one different constructors.
Two ways to distinguish between constructors
- Different Names
- Different Number and Types of Parameters
class box
{
protected:
int height;
int width;
public:
box(); //default constructor
box(int,int); //parameterized constructor
};