0% found this document useful (0 votes)
10 views36 pages

Class and Constructor

The document provides an overview of Object Oriented Programming (OOP) concepts, focusing on classes and objects in C++. It explains the structure of a class, including data members, methods, constructors, and access specifiers, and provides examples of classes such as Rectangle and BankAccount. Additionally, it covers advanced topics like static members, friend functions, and the importance of public vs private access in class design.

Uploaded by

mushrure.ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
10 views36 pages

Class and Constructor

The document provides an overview of Object Oriented Programming (OOP) concepts, focusing on classes and objects in C++. It explains the structure of a class, including data members, methods, constructors, and access specifiers, and provides examples of classes such as Rectangle and BankAccount. Additionally, it covers advanced topics like static members, friend functions, and the importance of public vs private access in class design.

Uploaded by

mushrure.ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Object Oriented Programming (OOP) Cys Oriented Cee) Concepts Nr Naa Ue Later) eT elie) C++: What is a Class? A class is a blueprint to create objects. It groups data (what it has) and methods (what it can do) into one new type. Data (fields): variables stored inside each object (e.g., balance). Methods: functions that act on that data (e.g., deposit (), withdraw ()). Access: private, protected, public. Constructor: special method with the same name of class; it initializes an object's data. Object: instance of class; one real thing made from the class or blueprint. Takeaway: Class = your own type; object = a variable of that type; methods = actions you can perform on the object. Class and Object — le name . rollNo wd > setName() fj ‘ ; setRoliINo() Class and Object Breed: Bulldog Size: large Colour light gray Ager 5 years DogiObject pe Breed: Beagle Size: large Colour: orange Age: 6 years Dog20bject oo Breed: German Shepherd Size: large Colour: white & orange Age: 6 years DogsObject |_—_] Methods Eat() Run() Sleep() Name() Example-1: Rectangle Class Define a class to represent a rectangle. Include: Data members e Length ¢ Width Member functions e Assign initial values (read length and width) © Compute area ¢ Compute perimeter ¢ Display length, width, area, perimeter Example-1: Rectangle Class 1 // Only , simple types 2 #include s using namespace std; 4 s class Rectangle { 6 private: 7 float length; 8 float width; 9 10 public: n // Constructor (Option 1: assign inside the body) 2 Rectangle() { length = 0.0£; width = 0.0f; } 8 4 // Assign initial values from user 1s void assignInitial() { 6 cout << Enter length and width: ; 7 cin >> length >> width; 9 10 " 2 he gle Class // Compute area and perimeter { return length * width; } float area() float perimeter () // Display all values void display() const { cout cout cout cout cout } << << << << << // end class { return 2 * (length + width); \n--- Rectangle ---\n; Length << length << \nj Width << width << \n; Area << area() << \nj Perimeter << perimeter ()<< \n; } Example-1: Rectangle Class 1 int main() { 2 Rectangle r; // create object 3 [Link](); // read input 4 [Link](); // show output 5 return 0; Example-2: Account Class Define a class to represent a bank account. Include: Data members © Name of depositor ¢ Account number © Type of account ¢ Balance amount Member functions ¢ Assign initial values © Deposit an amount ¢ Withdraw an amount (after checking balance) ¢ Display name and balance Example-2: Account Class // Only , beginner-friendly I/O #include using namespace std; 2 3 s class BankAccount { © private: 7 char name[50]; // depositor name 8 int aceNo; // account number 8 char accType; // 'S' = Savings, 'C' = Current 0 float balance; // balance amount 1 4 7 8 public: // Constructor (Option 1: assign inside the body) BankAccount () { name [0] = '\0'; accNo accType = 'S'; balance = 0.0f; Exampl Account Class 1 4 7 ° 2 // Deposit void deposit (float amount) { if (amount > 0.0£) balance += amount; else cout << Invalid deposit amount.\n; y // Withdraw (with check) void withdraw(float amount) { if (amount <= 0.0£) { cout << Invalid withdrawal amount .\nj; } else if (amount > balance) { cout << Insufficient funds. Available: balance << \n; } else { balance -= amount; } } // Display << Example-2: Account Class int main() { BankAccount acc; [Link](); 3 5 6 7 float dep; 8 cout << \nAmount to deposit: ; 9 cin >> dep; ° acc. deposit (dep) ; 1 2 float wd; 3 cout << Amount to withdraw: 4 cin >> wd; 5 [Link] (wd) ; 7 8 acc. display (); return 0; Memory Allocation for Multiple Objects Object 1 Object 2 Object n Data 1 Data Data 1 Data 2 Data2 Data 2 Data m Data m Data m Funetionl 0 Function? 0 Function3 0 Function k 0 Constructors — Concept Definition: A constructor is a special member function that initializes objects of its class. Key facts ¢ Name is same as the class; no return type. ¢ Runs automatically when an object is created. © Default constructor: takes no parameters. © Used to set safe initial values for data members. Style used here: Option 1 — assign inside the constructor body (not an initializer list). Constructors — Example (Default) /* class with a constructor */ class integer { int m,n; public: integer (void) ; // constructor declared MT ves ui // constructor defined (Option 1: assign in body) integer: : integer (void) { m= 0 n=0 Parameterized Constructors (C++) /* class with a parameterized constructor */ class integer ( int m, nj public integer(int x, int y); | // parameterized constructor LF. se DH // definition (Option 1: assign in body) integer: :integer(int x, int y) { m n xi vi > // usage // integer a(5, 9); // integer b = integer(10, 20); Parameterized Constructo Full Example 1 #include 2 using namespace std; 3 4 class integer 5 6 int m,n; 7 public: 8 integer (int, int); // constructor declared 10 void display (void) // member function Mn { 2 cout < Clan) (Ole) ter (part 2) finclude using namespace std; class Counter { int value; int step; public: // 3) Two-parameter constructor Counter(int start, int by) { value = start; step = by; ) void increment () { value += step; } int get () const ( return value; } 1; // end class Note (Option-1): assign inside constructor bodies (no initializer lists). Using the Overloaded Constructors 1 int main() { 2 Counter cl; // default -> value=0, 3 Counter ¢2(10); // one-arg -> value=10, step=1 4 Counter ¢3(100, 5); // two-arg -> value=100, step=5 5 6 cl. increment (); 0-4 7 [Link] (); // 10 -> 11 8 3. increment (); // 100 -> 105 0 cout << [Link]() << << [Link]() << << [Link]() << \nz 1 return 0; 2|y Example output: 1 11 105 Static Data Members — Concept What is it? A static data member is a class variable shared by all objects of that class. Key characteristics © Single copy for the entire class: every object uses the same storage. © Zero-initialized before the first object is created (unless you explicitly initialize it). ° Best for values common to all objects (e.g., counters, global settings). Why use it? To keep information that belongs to the class as a whole, not to any particular instance. e A destructor runs automatically when an object goes out of scope (e.g., end of main() or a {block}). ¢ You can use it to print a message or update counters—no pointers needed. e Name: ~ClassName () — no parameters, no return type. Tiny Example: Messages 0 eate/Destroy +#include using namespace std; class Greeter { public: Greeter() ( cout << Constructor: Hello! \nj > “Greeter() { cout << Destructor: Bye! \ny ) M int main) ( cout << Enter seope\n ( Greeter g; // constructor prints Hello! cout << Inside block\nj ) // destructor prints Bye! here (end of block) cout << Back to outer scope\n; return 0; // any remaining objects would be destroyed here Friend Function: Conce| ¢ A friend function is not a member of the class, but it is granted access to that class's private/protected members. ¢ Declared inside the class with the friend keyword; defined outside like a normal function. Called like a regular function, e.g., volume (b) — not [Link](). Friendship is neither inherited, nor transitive, nor reciprocal. ¢ Common uses: operator<>, binary operators, tight inter-class cooperation. Worked Example: Box with a Friend Functi finclude 2 using namespace std; 3 4 class Box { 5 private: 6 double w, hy dy // width, height, depth 7 public: 8 Box(double W, double H, double D){w=W; hel; d=D;} 9 0 // friend declaration: grants access to private w,h,d 1 Eeiend double volume (Box &b) 7 2 3. // (for comparison) a regular member too 4 double diag() { return (wew + heh + dea); } 5} 7 // friend definition (non-member) 8 double volume(const Box sb) { 9 sreturn b.w x b.h * [Link] // can read private fields 20} Using a Friend Function (Call Site) 1 int main() { 2 Box b1(2.0, 3.5, 4.0); 3 double v = volume (b1); // friend function call 4 // Note: we don't call [Link]() because it's not a member 5 6 7 std::cout << Volume = << v << \n; // 28.0 return 0; } Public vs Private Access public: anyone can use it (from outside the class). ¢ private: only the class itself can use it. © Why private? To protect data and avoid wrong/unsafe changes. ¢ Tip: In a class, things are private by default. In a struct, they are public by default. Public vs Private Access: Example finclude using namespace std; class Student { private: nt marks? // private: hidden public string name; // public: open Student () ( // Option-1: assign in body name = NoName; marks = 0; void setMarks(int m) { if (m >= 0 && m <= 100) marks = mj // simple check ) int getMarks() const { return marks; Public vs Private Access: Example int main() { 1 2 Student s; 3 [Link] = Asha; // allowed (public) 4 [Link] (85) ; // allowed via function 5 cout << [Link] << << [Link]() << \n; 6 7 // [Link] = 200; // ERROR: 'marks' is private 8 return 0; 9)} Idea: Keep data private; use simple public functions to set/get safely. Public vs Private Access: Another Example class Box { public: int width; // public private: int secretCode; // private 2 a 6 public: 7 8 9 0 Box() ( width = 10; secretCode = 1234; 0 } int getCode() const { // controlled read 2 return secretCode; 3 } ae 6 int main() ¢ 7 Box by 8 bewidth = 20; // OK (public) 9 // [Link] = 999; // ERROR (private) 2 int code = [Link](); // OK via function 2” return 0; Static Member (Code) include sing namespace std; ase iten static int count; // shared among all objects int number; // per-object data public: void getdata(int a) ‘ number count++; // update shared counter } void getcount () i cout << count: ; cout << count << \nz Static Member (Code) int item::count; // definition (zero-initialized) int main() ‘ item a, b, cj // count is initialized to zero [Link] (); // display count [Link] (); [Link] (); [Link](100); // getting data into object a [Link](200); // getting data into object b [Link](300); // getting data into object ¢ cout << After reading data << \ny [Link] (); // display count [Link] (); [Link] (); return 0; Expected Output count: 0 count: 0 count: 0 After reading data count: 3 count: 3 count: 3 Expected Output Otiect 4 Object 2 Object 3 umber umber = 3 ‘count (common to all wee cbyects)

You might also like