C++ Classes and Objects
C++ is an object oriented language. A class is a blueprint, and an object is a real thing made from it. A class has data members (variables) and member functions (methods).
#include <iostream>
#include <string>
class Student {
public:
std::string name;
int marks = 0;
void show() const {
std::cout << name << " scored " << marks << '\n';
}
}; // do not forget this semicolon
int main() {
Student s1; // an object on the stack
s1.name = "Riya";
s1.marks = 88;
Student s2{"Aman", 72}; // aggregate initialization
s1.show();
s2.show();
}
Output
Riya scored 88
Aman scored 72
Every object has its own copy of the data members. The const after show() means the method does not change the object.
Define a method outside the class
#include <iostream>
class Counter {
public:
void increment();
int value() const;
private:
int count = 0;
};
void Counter::increment() { count++; } // Class::method
int Counter::value() const { return count; }
int main() {
Counter c;
c.increment();
c.increment();
std::cout << c.value() << '\n';
}
Output
2
In real projects the class is declared in a header file (.h) and the methods are defined in a .cpp file.
struct and class
A struct is the same as a class, but its members are public by default, and a class has private by default. Use struct for simple data, and class for things with behavior.
#include <iostream>
struct Point {
int x = 0;
int y = 0;
};
int main() {
Point p{3, 4};
std::cout << p.x + p.y << '\n';
}
Output
7
Objects and pointers
#include <iostream>
#include <memory>
#include <string>
struct Pet {
std::string name;
void speak() const { std::cout << name << " says hi\n"; }
};
int main() {
Pet a{"Tommy"};
a.speak(); // dot for an object
auto b = std::make_unique<Pet>(Pet{"Kitty"});
b->speak(); // arrow for a pointer
}
Output
Tommy says hi
Kitty says hi
Note:
Keep data members private and give public methods. We learn that in Access Specifiers and Encapsulation. First, the constructors. Next: C++ Constructors and Destructors.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |