Classes and Objects in C++: Defining Types and Creating Instances
What is Classes and Objects in C++: Defining Types and Creating Instances? A class is defined using the class keyword containing data members and member functions. Objects can be instantiated automatically on the stack (automatic stora...
How are classes defined and instantiated in C++, and how do stack and heap allocations differ?
Explanation & In-Depth Details
A class defines the layout of bytes in memory. The size of an object equals the sum of its non-static data members plus alignment padding:
```text
STACK ALLOCATION vs HEAP ALLOCATION:
Stack: [BankAccount Object: balance(8B) | accountNumber(32B)] -> Automatic Scope Cleanup
Heap: Stack Pointer (8B) ──► Heap Memory [BankAccount Object] -> Manual delete / Smart Pointer
```
2. Member Access:
- Direct object: use dot operator `obj.member()`
- Pointer to object: use arrow operator `ptr->member()` or `(*ptr).member()`
Code Example
#include <iostream>
#include <string>
#include <memory>
class BankAccount {
private:
std::string accountNumber;
double balance;
public:
BankAccount(std::string accNum, double initialDeposit)
: accountNumber(std::move(accNum)), balance(initialDeposit) {}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
std::cout << "Deposited $" << amount << ". New balance: $" << balance << "\n";
}
}
void displayInfo() const {
std::cout << "Account: " << accountNumber << " | Balance: $" << balance << "\n";
}
};
int main() {
// 1. Stack Allocation (Automatic)
BankAccount stackAcc("ACC-STACK-101", 1500.0);
stackAcc.deposit(350.0);
stackAcc.displayInfo();
// 2. Heap Allocation with Smart Pointer (Modern Best Practice)
auto heapAcc = std::make_unique<BankAccount>("ACC-HEAP-909", 5000.0);
heapAcc->deposit(1000.0);
heapAcc->displayInfo();
return 0;
}Interview Question & Tips
A: In a class, members and base classes are private by default. In a struct, members and base classes are public by default.
Q: What is the size of an empty class in C++ and why?
A: An empty class has a size of 1 byte (non-zero) to ensure distinct objects of that class have unique memory addresses.
Best Practices
• Mark member functions that do not alter member variables with `const`.
• Pass complex objects by const reference `const Type&` to avoid unnecessary deep copying.
This study reference for Classes and Objects in C++: Defining Types and Creating Instances is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: