1 Class and Object
1 Class and Object
Create a Class
A class is defined in C++ using the keyword class followed by the name of the
class. The body of the class is defined inside the curly brackets and terminated
by a semicolon at the end.
Create an 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 access the class attributes (myNum and myString), use the dot
syntax (.) on the object:
int main() {
MyClass myObj; // Create an object of MyClass
Example 2
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
#include <iostream>
}
#include <string>
using namespace std;
Output:-- 15
Kush
Syntax:--
class class_name{
class class_name{
public:
public:
return_type Method_name()
return_type Method_name()
// method inside class
// method inside class definition
definition
{
{
// body of member function
}
// body of member function
};}
};
Example
#include <iostream>
#include <string>
using namespace std;
The member function is defined outside the class definition it can be defined
using the scope resolution operator. Similar to accessing a data member in the
class we can also access the public member functions through the class object
using the dot operator (.).
Syntax:
class Class_name{
public:
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}