C++ Classes and Objects: Structure, Member Functions & The 'this' Pointer

A Class is a user-defined blueprint from which individual Objects are created. An object is an actual instance occupying physical RAM with concrete data values.

Class Declaration & Method Implementation

#include <iostream>
#include <string>

class Employee {
private:
    int id;
    std::string name;
    double salary;

public:
    // Member function to set data (using 'this' to disambiguate names)
    void setData(int id, const std::string& name, double salary) {
        this->id = id;
        this->name = name;
        this->salary = salary;
    }

    void displayProfile() const {
        std::cout << "Employee ID: " << id << " | Name: " << name << " | Salary: $" << salary << "\n";
    }
};

int main() {
    // 1. Stack Allocation (Automatic lifetime)
    Employee emp1;
    emp1.setData(101, "Alice", 85000);
    emp1.displayProfile(); // Uses dot operator (.)

    // 2. Heap Allocation (Pointer access)
    Employee* empPtr = new Employee();
    empPtr->setData(102, "Bob", 92000);
    empPtr->displayProfile(); // Uses arrow operator (->)
    delete empPtr;

    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between a class and a struct in C++?

In C++, the only difference between a class and a struct is the default access level: members of a 'class' are private by default, whereas members of a 'struct' are public by default. Both support member functions, inheritance, and constructors identically.

Q2. What is the hidden 'this' pointer in C++?

The 'this' pointer is an implicit constant pointer automatically passed as a hidden first argument to all non-static member functions, holding the address of the specific object instance calling the function.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Constructors & Destructors

Object initialization and cleanup mechanics.

Access Specifiers

public, private, and protected member visibility.

OOP Concepts

Review the 4 core pillars of object orientation.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!