top of page

Specifying a Class, Defining Data Members, and Member Functions in C++

Writer: compnomicscompnomics

Understanding Classes

In C++, a class is a blueprint for creating objects. It defines the structure and behavior of those objects. A class consists of data members (attributes) and member functions (methods).

Specifying a Class

To specify a class, you use the class keyword followed by the class name. The class body is enclosed in curly braces ({}).

C++

class MyClass {
    // Data members
    // Member functions
};

Defining Data Members

Data members are variables that store the data associated with an object. They can be of any valid C++ data type (e.g., int, float, char, string).

C++

class Person {
public:
    string name;
    int age;
};

Defining Member Functions

Member functions are functions that operate on the data members of a class. They can be used to access, modify, or process the data associated with an object.

C++

class Person {
public:
    string name;
    int age;

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

Creating Objects

To create an object from a class, you use the new operator or simply declare a variable of that class type.

C++

Person person1;
Person* person2 = new Person();

Accessing Data Members and Calling Member Functions

You can access the data members and call the member functions of an object using the dot operator (.).

C++

person1.name = "Alice";
person1.age = 25;
person1.displayInfo();

Example Program

C++

#include <iostream>
#include <string>

using namespace std;

class Circle {
public:
    double radius;

    double calculateArea() {
        return 3.14159 * radius * radius;
    }
};

int main() {
    Circle myCircle;
    myCircle.radius = 5.0;

    cout << "Area of the circle: " << myCircle.calculateArea() << endl;

    return 0;
}

Output:

Area of the circle: 78.5398

In this example, the Circle class has a data member radius and a member function calculateArea(). The main function creates a Circle object and sets its radius. Then, it calls the calculateArea() function to calculate and print the area of the circle.

 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page