Define and declare class, data member and member function in C++

In the world of C++, a class acts like a blueprint or building block for Object-Oriented Programming. It encapsulates its own set of data members and member functions. These components can be accessed by creating instances of the class.

Defining a Class in C++

class ClassName {
    Access specifier;         // It can be private, protected, or public
    Data members;             // Variables to be used
    Member Functions(){}      // Methods to access data members
};

A member function of the class uses data members collectively to define the properties and behavior of the class.

Creating Objects

An object is an instance of the class, and one or more objects can be created. When a class is defined, memory is allocated. As class instances, declared as objects, are created, memory is allocated to them.

Syntax for Object Creation and Accessing Members

ClassName ObjectName;                      // Declare the Object
ObjectName.DataMemberName;                  // Accessing the Data Member
ObjectName.MemberFunctionName();            // Accessing the Member Function

Code Example

#include<iostream>
using namespace std;

class Example {
public:
    string name;

    void printName() {
        cout << "Member function name: " << name;
    }
};

int main(){
    Example obj1;
    obj1.name = "printName";
    obj1.printName();
    return 0;
}

Output:

Member function name: printName

Defining Member Functions

There are two methods to declare member functions: inside the class and outside the class.

Define Inside the Class

class ClassName {
public:
    void inside() {
        // Function definition
    }
};

Define Outside the Class

class ClassName {
public:
    void outside();
};

void ClassName::outside() {
    // Function definition
}

Code Example for Inside and Outside Definitions

#include<iostream>
using namespace std;

class Example {
public:
    string name1;
    string name2;

    void inside() {
        cout << "Inside member function name: " << name1 << endl;
    }

    void outside();
};

void Example::outside() {
    cout << "Outside member function name: " << name2;
}

int main(){
    Example obj1;
    obj1.name1 = "indoor";
    obj1.name2 = "outdoor";
    obj1.inside();
    obj1.outside();
    return 0;
}

This example illustrates defining member functions both inside and outside the class.

Next Post Previous Post
No Comment
Add Comment
comment url