Oop 3
Oop 3
Oop 3
Bipasha Majumder
Lecturer, Dept of CSE
Dhaka International University
1
C structures revisited
Structure is unique feature in C language. Structures
provide a method for packing together data of different
types.
// structure example int main ()
struct student {
{ struct student a;
char name[20]; a.name=“Rhahim";
int roll; a.roll=111;
}; }
ClassName ObjectName;
Data Hiding with Access Specifier
Data hiding is the key feature of OOP.
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from
outside the class
protected - members cannot be accessed from outside
the class, however, they can be accessed in inherited
classes. You will learn more about Inheritance later.
If the labels are missing, then, by default, all the
members are private.
6
Program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class day_73 {
// Access specifier
public:
// Data Members
string name;
int id;
// Member Functions()
void print()
{ cout << "Name is:" <<name<<" "<<"Roll is:"<<id<<endl; }
};
int main()
{
// Declare an object of class day_73
day_73 obj1; Output:
// accessing data member
obj1.name = "Anis"; Name is:Anis Roll is:12
obj1.id=12;
// accessing member function
obj1.print();
return 0;
} 7
Create multiple objects of a class
Same as before.....
int main()
{
// Declare multiple object of class day_73
day_73 obj1,obj2;
// accessing data member
obj1.name = "Anis";
obj1.id=12;
obj2.name = "Jahid";
obj2.id=13;
Output:
// accessing member function Name is:Anis Roll is:12
obj1.print(); Name is:Jahid Roll is:13
obj2.print();
return 0;
} 8
Can we apply class_object concept without member
function?
Ans: Yes, you can! Need to print it manually without calling member function. But
good practice is using member function.
#include <bits/stdc++.h>
using namespace std;
class day_73 {
public:
string name;
int id;
}; Output:
int main()
{
Name:Anis Roll:12
day_73 obj1;
obj1.name = "Anis";
obj1.id=12;
cout << "Name:" <<obj1.name<<" "<<"Roll:"<<obj1.id<<endl;
return 0;
} 9
Take input from user and Print it!!
#include <bits/stdc++.h>
using namespace std;
class day_73 {
public:
string name;
int id;
};
int main()
{
day_73 obj1;
Cin>>obj1.name>>obj1.id;
cout << "Name:" <<obj1.name<<" "<<"Roll:"<<obj1.id<<endl;
return 0;
}
10
Practice!!
Create a class named 'Student' with a string variable
'name‘, an integer variable 'roll_no‘, and floating
variable ‘cgpa’. Now, creating at least two object of the
class Student and print it.
11
Quiz 1!
What is the difference between struct and class in C++?
12
Quiz 2!
Predict the output?
class Test {
int x;
};
1. 0
int main()
{ 2. Garbage Value
Test t; 3. Compiler Error
cout << t.x;
return 0;
}
13