C++ Object Class OOPs Concepts
Syntax
The syntax to declare a class in C++ is as follows:
class ClassName {
// Member variables and functions
};
And to create an object of a class, use the following syntax:
ClassName objectName;
Example
Let's say we want to create a class called "Person" with two member variables: name and age.
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
};
int main() {
Person person1; // Create object person1
person1.name = "John";
person1.age = 25;
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
return 0;
}
Output
The output of the example above will be:
Name: John
Age: 25
Explanation
In the example above, we have created a class called "Person" with two member variables: name and age. We have also created an object of the class called "person1" and initialized its member variables using dot notation. Finally, we have printed the values of name and age using cout statements.
Use
Classes in C++ are used to create user-defined data types, which can then be used to create objects. Objects can be used to store and manipulate data, which makes programming more efficient and organized.
Important Points
- A class is a blueprint or template for creating objects.
- A class can have member variables and member functions.
- Member variables are the data members of a class and member functions are the functions that provides behavior to the object of the class.
- Access specifiers (public, private and protected) can be used to control the access of the members of a class.
- Objects are instances of a class.
Summary
In this tutorial, we learned about the C++ object class OOPs concepts. We learned how to declare a class, create an object of a class, and how to access the member variables and member functions of a class. We also discussed the importance of classes in C++ and how they can be used to create user-defined data types.