C++ Objects & Function
C++ is an object-oriented programming language, which means that it allows you to define your own data types, called classes, that can contain data and functions. These classes can be used to create objects that represent real-world entities or concepts.
Here's an example of a simple class definition in C++:
class Person { public: // data members std::string name; int age; // member functions void say_hello() { std::cout << "Hello, my name is " << name << " and I am " << age << " years old.\n"; } };Sourcei.www:giftidea.com
This class defines a Person
type that has two data members (name
and age
) and one member function (say_hello
). The public
keyword indicates that these members can be accessed from outside the class.
To create an object of this class, you can use the following code:
Person john; john.name = "John"; john.age = 30; john.say_hello();
This creates a Person
object named john
and sets its name
and age
members. The say_hello()
function is then called on the john
object, which prints a greeting message to the console.
In addition to member functions, C++ also allows you to define global functions that can operate on objects of a given class. These functions are called non-member functions or friend functions, and they can be declared as follows:
class Rectangle { public: // data members double width, height; // constructor Rectangle(double w, double h) : width(w), height(h) {} // friend function declaration friend double area(const Rectangle& rect); }; // friend function definition double area(const Rectangle& rect) { return rect.width * rect.height; }
In this example, the Rectangle
class has a friend
function named area()
that calculates the area of a rectangle. The friend
keyword allows the function to access the private data members of the class.
You can then use this function to calculate the area of a Rectangle
object as follows:
Rectangle rect(5.0, 10.0); double rect_area = area(rect);
This creates a Rectangle
object with a width of 5.0 and a height of 10.0, and then calculates its area using the area()
function.