Creating Classes and Objects in C++

C++ is a powerful programming language that supports object-oriented programming (OOP) paradigms. One of the fundamental concepts in OOP is the creation of classes and objects. A class is a blueprint for creating objects, while an object is a specific instance of a class.

Creating a Class

To create a class in C++, we use the class keyword followed by the class name. Let's take an example of a class called Person:

class Person {
  // Class members
};

Inside the class, you can declare various members such as data members and member functions. Data members represent the attributes or characteristics of objects, while member functions define the behaviors or operations that objects can perform.

class Person {
  private:
    string name;
    int age;
  
  public:
    void setName(string newName) {
      name = newName;
    }

    void setAge(int newAge) {
      age = newAge;
    }

    void displayInfo() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
    }
};

In the above example, we have two data members: name and age, along with three member functions: setName(), setAge(), and displayInfo(). The private access specifier ensures that these data members can only be accessed by member functions inside the class.

Creating Objects

Once the class is defined, we can create objects of that class. Objects are created using the class name followed by the object name and the parentheses (). The parentheses are used to invoke the constructor, which initializes the object.

Person person1;
Person person2;

In the above example, two objects, person1 and person2, of the Person class are created.

Accessing Class Members

To access the members of a class, we use the dot operator .. The dot operator allows us to access the members of an object.

person1.setName("John Doe");
person1.setAge(25);

person2.setName("Jane Smith");
person2.setAge(30);

person1.displayInfo();
person2.displayInfo();

In the above example, we use the dot operator to call the member functions setName(), setAge(), and displayInfo() for person1 and person2. We can set the name and age values for each person object and then display their information using the displayInfo() function.

Conclusion

Creating classes and objects is an essential aspect of object-oriented programming in C++. By defining classes, we can encapsulate data and related behaviors into objects, allowing for more flexible and modular code. Understanding these concepts will help you in building efficient and structured programs.


noob to master © copyleft