Lecture 2
Lecture 2
Programming
Class
In programming
A class is like a user-defined data type.
A class is a collection of data and functions, the data items and
functions are defined within the class.
1- Data members
(Data items used to represent attributes/characteristics/properties of an object)
2-Member functions/methods
Functions used to work on its data members are called member functions or methods.
batavg float
batname 10 character
Calavg() (Function to compute float
batsman avegerage )
Public Member:
readdata() void
detail: Function to accept
value from Batcode, name,
innings, not_out and invoke the
function Calcavg()
displaydata() Void
Detail: Function to display the
data members on the screen
Class UML Diagram
Difference between classes
and structures
• Technically speaking, structs and classes are almost
equivalent
• The major difference like class provides the flexibility of
combining data and methods (functions ) and it provides
the re-usability called inheritance.
• A class has all members private by default. A struct is a
class where members are public by default
Difference between classes
and structures
• // Program 1
• #include <stdio.h>
•
• struct Test {
• int x; // x is public
• };
• int main()
• {
• Test t;
• t.x = 20; // works fine because x is public getchar();
• return 0;
• }
Difference between classes
and structures
• // Program 2
• #include <stdio.h>
•
• class Test {
• int x; // x is private
• };
• int main()
• {
• Test t;
• t.x = 20; // compiler error because x is private
• getchar(); return 0;
• }
Encapsulation /
Information Hiding/ Data
Hiding
• Information hiding is one of the most important principles of OOP
inspired from real life which says that all information should not be
accessible to all persons.
2) It is used to reduce the human errors. The data and function are
bundled inside the class that take total control of maintenance and thus
human errors are reduced.
2- No one can access the information/ contacts of your cell phone if you
locked memory of your cell phone with some password.
3- While you login to your email, you must need to provide the hidden
information (Password) to your server.
Encapsulation
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
Class Activity
#include<iostream>
using namespace std; Class Activity
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;