In: Computer Science
Explain what classes and objects are in object - oriented programming. Give an example of each and explain how they work together in a computer program.
In object oriented programming language, class is a user defined data type and it is a blueprint of creating objects i.e set of instructions to build an object and class holds data members and member functions.
where object is an instance of a class, generally when we create a class there is no memory allocaion occurs but when a object is created which is also called class is instantiated there it allocates memory. through object we can access data members and member functions of a class outside of it .
generally we create a class as:
class Classname
{
//members
}
where class is keyword.
and we create object as : Classname objectName;
we can access data members of class throgh "." operator as objectName.member function()
Example:
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
using namespace std;
class C
{
public: //Access specifier
string Name; //data members
void Print()
{
cout<<"My Name is "<< Name;
}
};
int main()
{
C obj;
obj.Name="Alexa"; //Accessing data members
obj.Print(); //Accessing member function
return 0;
}
output: