#include <iostream>
using namespace std;
class Human {
public:
string Name;
void printName() {
cout << "Name of person: " << Name << endl;
}
};
int main() {
Human Object_1;
Object_1.Name = "John";
Object_1.printName();
return 0;
}
This C++ code creates a class called Human
. The class has one public attribute called Name
which is a string. It also has a public member function printName()
that prints the value of Name
.
The code then defines the main()
function which creates an object of the Human
class called Object_1
. It then assigns the value "John" to the Name
attribute of Object_1
using the dot notation.
Finally, the code calls the printName()
function of Object_1
which prints out "Name of person: John" to the console.
In object-oriented programming languages like C++, objects have state and behavior. The state represents the object's properties, while the behavior represents the object's actions or methods. To access an object's state or behavior, we need a way to refer to that object. That's where the dot notation comes in.
The dot notation is used to access an object's methods or properties. It is called the member access operator because it allows us to access the members (properties and methods) of the object. In C++, we use the dot notation to access an object's methods and properties after creating an instance of the class. The dot notation is a way of telling the program which object we want to access and what we want to do with it.
#include <iostream>
using namespace std;
class Human {
public:
string Name;
void printName() {
cout << "Name of person: " << Name << endl;
}
};
int main() {
Human Object_1;
Object_1.Name = "John";
Object_1.printName();
Human Man_2;
Man_2.Name = "Mr X";
Man_2.printName();
return 0;
}
The main()
function creates two Human
objects, sets their name using the Name
member variable and then calls the printName()
function on each object to display their respective names on the console.
No comments:
Post a Comment