Structs aur Classes
Ek struct related values ko ek naam wale type ke neeche saath mein group karta hai, jiske members name se directly accessible hote hain.
main.cpp
Khud try karo →#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;
}Output
Alice is 30 years old
class aur constructors
class har respect mein struct jaisa hi hai sirf ek cheez chhod 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 run hota hai — yeh ek naye object ki initial state set up karne ki natural jagah hai.
main.cpp
Khud try karo →#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;
}Output
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 karo jiske fields title (string) aur price (double) hon. Title "Dune" aur price 15.0 wali ek Book banao, phir "<title> costs <price>" print karo.