C++ is an object oriented programming language. Classes and objects are the way through which it implements its "object orientedness".
Classes are used to make user defined data types which we can use in our programs.
A class generally contains data members and member functions. A class is a blueprint from which any number of objects (which have certain attributes and functions) can be made. Data members (variables of class) are the attributes of the objects and member functions (functions declared / defined in the class) are the functions which define the behavior of the object.
Defining a Class
when a class is defined no memory is allocated. Memory is allocated for the object we create.
A class is used to make an object which resembles to real life objects. Following is a basic example of a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // person.h #pragma once using namespace std; class person { // defining a class named "person" public: // public access specifier string name; // two string variables string gender; // which are the attributes of the objects of this class. void speak(); // declaring the function which defines the behavior of the object }; void person::speak() { // defining "speak()" function // prints the name and gender of the person. cout << "My name is " << name << " and I am a " << gender << "." << endl; } |
void speak(); // declaring the function which defines the behavior of the object
void person::speak() { // defining a speak() function // prints the name and gender of the person. cout << "My name is " << name << " and I am a " << gender << "." << endl; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // person_1.h #pragma once using namespace std; class person { // defining a class named "person" public: // public access specifier string name; // two string variables string gender; // which are the attributes of the objects of this class. void speak() { // defining a speak() function // prints the name and gender of the person. cout << "My name is " << name << " and I am a " << gender << "." << endl; } }; |
void speak() { // defining a speak() function // prints the name and gender of the person. cout << "My name is " << name << " and I am a " << gender << "." << endl; }
Creating Objects from Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // program.cpp #include<iostream> #include "person.h" using namespace std; int main() { person obj1; // creating a person obj1.name = "Jack"; // assigning value to string variable "name" obj1.gender = "Male"; // assigning value to string variable "gender" obj1.speak(); // calling the speak function person obj2; // same process for another person obj2.name = "Hallie"; obj2.gender = "Female"; obj2.speak(); return 0; } |
obj1.name = "Jack"; // assigning value to string variable "name" obj1.gender = "Male"; // assigning value to string variable "gender"
obj1.speak(); // calling the speak function
Comments
Post a Comment
If you have any doubt, please let me know.