C++ Classes and Objects C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Classes and Objects
C++ Classes
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.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.
For example, we Creating the MyClass
using the keyword class as follows:
class MyClass{ // THE CLASS public: // Access specifier int length; // Attribute (int variable) double breadth; // Attribute (double variable) };
How to Create an C++ Object
In C++, an object is created from a class. We have already created the class named MyClass
, so now we can use this to create objects.
To create an object of MyClass
, specify the class name, followed by the object name and to access the class attributes (length
and breadth
), use the dot syntax (.
) on the object:
Example: Create an object called "myObj" and access the attributes:
#include <iostream>
#include <string>
using namespace std;class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};int main() {
MyClass myObj; // Create an object of MyClass// Access attributes and set values
myObj.length= 15;
myObj.breadth= 20;// Printing the values
cout << myObj.leangth<< "\n";
cout << myObj.breadth;
return 0;
}
Output:
15
20
Note: You can use create multiple objects of the same class and can set different values to it's attributes.
Example:
MyClass myObj1;
MyClass myObj2;
myObj1.length= 15;
myObj2.length= 16;