⚙️ C++ Beginner

What is a class and an object in C++?

Answer

A class is a user-defined blueprint or template that defines the data members (attributes) and member functions (methods) that objects of the class will have. A object is an instance of a class — a concrete entity created at runtime that holds its own copy of the data members. class Car { public: std::string brand; // data member int year; void startEngine() { // member function std::cout << brand << " engine started!\n"; } }; // Creating objects Car myCar; // Stack allocation myCar.brand = "Toyota"; myCar.year = 2022; myCar.startEngine(); Car* heapCar = new Car(); // Heap allocation heapCar->brand = "Honda"; delete heapCar;. Access specifiers: public — accessible from anywhere; private (default for class) — accessible only within the class; protected — accessible within class and derived classes. struct vs class: both define user-defined types. The only difference: struct members are public by default; class members are private by default. Use struct for passive data aggregates (POD types); use class for objects with behavior and invariants. Member initialization: prefer constructor initializer lists: Car(std::string b, int y) : brand(b), year(y) {} — more efficient than assignment in body (avoids default-construction then copy-assignment). this pointer: implicit pointer inside member functions pointing to the current object.