Defining classes in C++ involves creating a blueprint for objects that can be created from that class. The blueprint includes data members and member functions that define the properties and behaviors of the objects. Access specifiers control the visibility of the data members and member functions. Here’s an overview of how to define classes in C++:
1. Data members: Data members are variables that belong to each object of the class. They represent the state of the object and can be of any C++ data type. They are declared within the class definition. For example:
class Person { public: string name; int age; double height; };
In this example, the `Person` class has three data members: a string `name`, an integer `age`, and a double `height`.
2. Member functions: Member functions are functions that belong to each object of the class. They represent the behavior of the object and operate on the data members. They are declared within the class definition and can be defined within or outside the class definition. For example:
class Person { public: string name; int age; double height; void sayHello() { cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl; } };
In this example, a member function `sayHello()` is added to the `Person` class. It outputs a greeting that includesthe name and age data members of the object.
3. Access specifiers: Access specifiers control the visibility of the data members and member functions of the class. They can be `public`, `private`, or `protected`. `public` members are accessible from outside the class, while `private` members can only be accessed from within the class. `protected` members are similar to `private` members, but they can be accessed by derived classes. Access specifiers are declared within the class definition and apply to all members that follow until another access specifier is encountered. For example:
class Person { private: string name; int age; public: double height; void setName(string n) { name = n; } void setAge(int a) { age = a; } void sayHello() { cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl; } };
In this example, the `name` and `age` data members are declared as `private`, which means they can only be accessed by member functions of the `Person` class. The `height` data member is declared as `public`, which means it can be accessed from outside the class. `setName()` and `setAge()` are member functions that are used to set the `name` and `age` data members, respectively.
By defining classes inC++, you can create custom data types that can be used to represent real-world objects or complex data structures. Data members represent the state of the object, while member functions define the behavior of the object. Access specifiers control the visibility of the data members and member functions and ensure that the data members are accessed and modified in a controlled manner.