Structs aur Classes
Ek struct related values ko ek naam wale type ke neeche sath mein group karta hai, jiske members naam se directly accessible hote hain.
#include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int age;
};
int main() {
Person alice;
alice.name = "Alice";
alice.age = 30;
cout << alice.name << " is " << alice.age << " years old" << endl;
return 0;
}Alice is 30 years old
class aur constructors
class har respect mein struct jaisa hi hai sirf ek cheez chhor kar: struct ke members by default public hote hain, class ke by default private. Ek constructor ek special member function hai, jiska naam class jaisa hota hai, jo instance banne par automatically chalta hai — yeh ek naye object ki initial state set up karne ki natural jagah hai.
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) {
name = n;
age = a;
}
};
int main() {
Person bob("Bob", 25);
cout << bob.name << " is " << bob.age << " years old" << endl;
return 0;
}Bob is 25 years old
Aage: constructors aur RAII — woh ek idea jo idiomatic C++ mein garbage collector ki jagah leta hai.
Practice exercise
Ek struct Book define karein jiske fields title (string) aur price (double) hon. Title "Dune" aur price 15.0 wali ek Book banayein, phir "<title> costs <price>" print karein.