Unit-Ii Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

UNIT-II NOTES

C++ Classes and Abstraction:


Class definition:

It is a collection of data members & data functions like structure.

Class Structure & Class objects:

The general form of a class declaration is,

class class_name

private data & functions

public:

public data & functions

}object name list;

Ex:

#define SIZE 100

//This creates a class stack

Class stack

int stck[SIZE];

int tos;

public:

void init();
void push(int i);

int pop();

};

- A class may contain private as well as public parts. By default,


all items are private.
- For ex. stck & tos are private.
- These private data members only access the functions that are
data members.
- All other variables, or functions defined after public can be
accessed by all other functions in the program.
- The rest of your program accesses an object through its public
functions.
- The functions init(),push() & pop() are called member functions.
- The variables stck & tos are called member variables(data
member).
- Only member functions have access to the private members of
their class.
Only, init(), push() & pop() may access stck & tos.
- Once you have defined a class, you can create an object of that
type by using the calss name.
stack mystack;
- Mystack is a instance of stack.
- Class is a logical abstraction & while object is real(that ias, an
object exists inside the memory of the computer).
- Inside the class stack, members functions were identiofied
using their prototypes.
- When it comes time to actually code a function that is the
member of a class, you must tell the compiler which class the
function belongs to by qualifying it name with the name of a
class of which it is member.
- For ex., here is one way to code the push() function,
void stack::push(int i)
{
if(tos==SIZE)
{
cout<<”stack is full\n”;
return;
}

stck[tos]=i;

tos++;

}
- The :: is called the scope resolution operator.
- It tells the compiler that this version of push() belongs to the
stack class.
- Or, this push() is in stacks scope.
- In C++, several different classes can use the same function
same. The compiler knows which function belongs to which
class because of the scope resolution operator.
- When you refer to member of a class from a piece of code that
is not part of the calss, you must always do so in conjunction
with an object of that class to do so,

stack stack1,stack2;

stack1.init();

the remaining code,


void stack::init(){

tos=0;

int stack::pop()

if(tos==0){

cout<<”stack underflow \n”;

return 0;

tos--;

return stck[tos];

int main()

stack stack1,stack2; // create two stack objects

stack1.init();

stack2.init();

stack1.push(1);

stack2.push(2);

stack1.push(3);

stack2.push(4);
cout<<stack1.pop()<<” ”;

cout<<stack1.pop()<<” ”;

cout<<stack2.pop()<<” ”;

cout<<stack2.pop()<<” ”;

return 0;

Output:

3142

The this pointer:


i. It is used to retrieve the pointer address.
Like, we use ‘&’ operator in C to retrieve the address. In
C++, we use this pointer to know the current object
address.
ii. The this pointer is used to distinguish data member from
local variables. When both are declared with the same.
- usually, the variables are of two types, static &
non-static variables.
1. Every non-static member of C++, having local
variable called this.
2. the static member never contains this.
- it(this) returns address in hexadecimal format.

i. #include<iostream>

using namespace std;

class test

{
int a,b;

public:

void show()

a=10;

b=10;

cout<<”object Address is: ”<<this;//returns


//the current object address

cout<<”a=”<<this->a<<endl;

cout<<”b=”<<this->b<<endl;

};

int main()

test t;

t.show();

return 0;

ii. this pointer is used to distinguish data member &


arguments.

#include<iostrem>

using namespace std;


class test

int a,b;

public:

void show(int a,int b)

a=a;

b=b;

void display()

cout<<a<<endl;

cout<<b;

};

int main()

test t;

t.show(10,20);

t.display();
}

- In every programming, the local variables has the priority.


Here, in show() method both data member & local variables has
same name & data members are not recognized.
- In order to distinguish the data members & local variables we
use this pointer.
- The statement,
a=a;

b=b;

can be written as,

this->a=a; or (*this).a=a;

this->b=b; or (*this).b=b;

Friend classes:
- It is possible for one class to be a friend of another class.
- When this is the case, the friend class & all of its functions have
access to the private members defined within the other class.
- For ex.
- // using friend class
#include<iostream>
using namespace std;
class TwoValues
{
int a;
int b;
public:
TwoValues(int i,int j){
a=i;
b=j;
}
friend class Min;
};
class Min
{
public:
int min(TwoValues x);
};

int Min::min(TwoValues x)

return x.a<x.b?x.a:x.b;

int main()

TwoValues ob(10,20);

Min m;

cout<<m.min(ob);

return 0;

Output:

10
- In this ex., class Min has access to the private variables a & b
declared within the TwoValues class.
- It is critical to understand that when one class is a friend of
another, it only has access names defined within the other
class. It does not inherit the other class.
- Specifically , the members of the first class do not become
members of the friend class.

Static class members:


- Both function & data members of a class can be made static.

Static Data Members:

A static member variable has certain special characteristics,


- It is initialized to zero when the first object of its class is
created.
- Only one copy of that member is created for the entire class &
is shared by all the objects of that class, no matter how many
objects are created.
- It is visible only within the class, but its lifetime is the entire
program.
- Static variables are normally used to maintain values common
to the entire class.
- For ex., a static data member can be occurrences of all the
objects.
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}

void getcount(void)

cout<<”count”;

count<<count<<”\n”;

};
int item::count;
int main()
{
item a,b,c;

a.getcount(); // display count


b.getcount();
c.getcount();

a.getdata(100); // getting data into object a


b.getdata(200); //getting data into object b
c.getdata(300);// getting data into object c

cout<<”After reading data”<<”\n”;

a.getcount(); // display count


b.getcount();
c.getcount();
return 0;
}
Output:
count:0
count:0
count:0
After reading data
count:3
count:3
count:3

Static Member Functions:

- A member function that is declared static has the following


properties,
i. A static function can have access to only other static
members(functions, or variables) declared in the same
class.
ii. A static member function can be called using the class
name.
class_name::function_name();
below program illustrates the implementations of these
characteristics.
- The static function showcount() displays the number of objects
created till that moment.
- A count of member of objects created is maintained by the
static variable count.
- The function showcode() displays the code number of each
object.
#include<iostream>
using namespace std;
class test
{
int code;
static int count;
public:
void setcode(void)
{
code=++count;
}

void showcode(void)

cout<<”object number:”<<code<<”\n”;

static void showcount(void)

cout<<”count:”<<count<<”\n”;

};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}

Output:

Count:2

Count:3

Object number:1

Object number:2

Object number:3

const Member Functions:

- If a member functions does not alter any data in the class,


- Then we may declare it as a const member function as follows.
void mul(int,int) const;
double get_balance() const;
- The qualifier const is appended to the function prototypes(in
both declaration & definition).
- The compiler will generate an error message if such functions
try to alter the data values.

Constructor & Destructor:

Introduction:

- A.input(); // Initializes variables of object A.


- X.getdata(100,299.95);
- These function calls, can not be used to initialize the member
variables at the time of object creation.
- Like built in types, we can also create user-defined datatypes.
- This means that we can initialize a class type variables(objects)
when it is declared.
- As same as, initialization of an ordinary variable.
- When variable goes out of scope, it will be destroyed, but it is
not happened with the objects.
- C++ provides a special function called the constructor which
enables an object to initialize itself when it is created.

Constructor:

- A constructor is a special member function whose task is to


initialize the objects of its class.
- It is name is the same as the class name.
- It is invoked whenever an object of its associated class is
created.
- A constructor is declared & defined as follows,
class integer
{
int m;
int n;
public:
integer(void); //constructor declared
------------------
------------------
};

Integer::integer(void) //constructor defined

{
m=0;

n=0;

- intger int1; // not only creates object, initializes its data


//member to m & n zero.
- There is no need to write any statement to invoke the
constructor function(like normal member functions).
- A constructor that accepts no parameter is called the default
constructor.
- The default constructor for class a is A::A();
If no such constructor is defined, the compiler supports the
default constructor.

Characteristics of constructor function:

- They should be declared in the public function.


- They are invoked automatically when the objects are created.
- They do not return types, not even void.
- They can’t be inherited.
- Like C++ functions, they can have default arguments.
- We can not refer to their address.

Parameterized Constructor:

- In previous, we initialized, the data members of all the objects


to zero.
- In practice, we have to initialize the data member of object with
different value when they are created.
- This can be achieved by passing arguments constructor.
- The constructor which takes arguments called parameterized
constructor.
class integer
{
int m;
int n;
public:
integer(int x,int y);
--------------------------
--------------------------
};

Intger::integer(int x,int y)

m=x;

n=y;

- Here,
integer int1; //doesn’t works
- We have to pass arguments, to the constructor. This can be
done in two ways.
(i). By calling constructor explicitly
integer int1=integer(0,100);
(ii). By calling the constructor implicitly
integer int1(0,100);
Ex. This program defines a called point that stores the x & y
coordinates of a point.
#include<iotsream>
class point
{
int x;
int y;
public:
point(int a,int b)
{
x=a;
y=b;
}

void display()

Cout<<”C”<<x<<”,”<<y<<”)\n”;

};

int main()

point p1(1,1); //invokes parameterized constructor

point p2(5,10);

cout<<”Point p1=”;

p1.display();

cout<<”Point p2=”;

p2.display();

return 0;

Output:

Point p1=(1,1)
Point p2=(5,10)

Multiple Constructor in a Calss:


class integer
{
int m;
int n;
public:
integer() //constructor1
{
m=0;
n=0;
}

integer(int a,int b)

m=a;

n=b;

integer(integer &i)

m=i.m;

n=i.n;

};

int main()
{

integer I1;

integer I2(20,40);

integer I3(I2);

return 0;

Constructor with Default Arguments:

- It is possible to define constructor with default arguments.


- For ex. The constructor complex can be declared as,
complex(float real,float imag=0);
the default value of argument imag is zero.
- complex c(5.0); // real=5.0,imag=0
- complex c(2.0,3.0);
//real=2.0, imag=3.0
- the difference between default constructor & default argument
constructor.
- The default argument constructor can be called with either one
argument or no arguments.

Copy constructor:

- A copy constructor is used to declare & initialize an object from


another object.
Integer I2(I1);
//The above statement define object I2 & initializes it to the
values of I1.
- Another form is,

Integer I2=I1;
- integer(integer &i);
#include<iostream>
using namespace std;
class code
{
int id;
public:
code()
{
}

code(int a)

id=a;

code(code &x) //Copy constructor

id=x.id;

void display()

cout<<id;

};

int main()
{

code A(100); //object created & initialized

code B(A); //copy constructor called

code C=A; // copy constructor called

code D; // D is created & not initialized

cout<<”\n id of A:”;

A.display();

cout<<”\n id of B”;

B.display();

cout<<”\n id of C”;

C.display();

cout<<”\n id of D”;

D.display();

return 0;

Output:

Id of A:100

Id of B:100

Id of C:100

Id of D:100

Destructor:
- it is used to destroy the objects that have been created by a
constructor.
- Like constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a tilde.
- For ex. The destructor for the class integer can be defined as
shown below,
~integer()
{
}
- A destructor never takes any argument nor does it return value.
- It will be invoked implicitly by the compiler upon exist from the
program(or block or function etc).
- The ex. Below illustrates that the destructor has been invoked
implicitly by the compiler.
#include<iostream>
using namespace std;
int count=0;
class test
{
public:
test()

count++;
cout<<”\n Constructor Msg:object number”;

~test()

{
cout<<”\n Destructor Msg:object
number”<<count<<”destroyed”;

count—;

};

int main()

cout<<”Inside the main block.”;

cout<<”\n\n Creating first object T1..”;

test T1;

cout<<”\n \n Inside Block..”;

cout<<”\n \n Creating two more objects T2 & T3..”;

test T2,T3;

cout<<”\n\nLeaving Block1..”;

cout<<”\n \n Back inside the main block”;

return 0;

Output:

Inside the main block

Creating first object T1


Constructor Msg:Object number 1 created

Inside block 1

Creating two more objects T2 and T3

Constructor Msg:Object number 2 created

Constructor Msg:Object number 3 created

Leaving Block1..

Destructor Msg:Object number 3 destroyed

Destructor Msg:Object number 2 destroyed

Back inside the main block

Destructor Msg:object number 1 destroyed

Dynamic creation & destruction of objects:

- C++ supports dynamic memory allocation & de-allocation.


- C++ allocates memory & initializes the member variables.
- A object can be created at run-time; such an object is called a
dynamic object.
- The construction & destruction of the dynamic object is
explicitly done by an programmer.
- The new & delete operator are used to allocate & de-allocate
memory to such objects.
- A dynamic object can be created using the new operator as
follows.
ptr=new classname;
- The new operator returns the address of the object created & it
is stored in the pointer ptr.
- The variable ptr is a pointer object of the same class.
- The member variable of the object can be accessed using the
pointer -> (arrow) operator.
- A dynamic object can be destroyed using delete operator as
follows.
delete ptr;
- The delete operator destroys the object pointed by the pointer
ptr.
- It also invokes the destructor of a class.
- The following program explains the creation & destruction of
dynamic objects.
#include<iostream>
using namespace std;
class data
{
int x;
int y;
public:
data()
{
cout<<”\n Constructor”;
x=10;
y=50;
}

~data()

cout<<”\n Destructor ”;

void display()
{

cout<<”\n x=”<<x;

cout<<”\n y=”<<y;

};

int main()

data *d; // declaration of object pointer

d=new data; //dynamic object

d->display();

delete d; //deleting the dynamic object

return 0;

Output:

Constructor

x=10

y=50

Destructor

Data Abstraction:
- Data Abstraction is a process of providing only the essential details
to the outside world and hiding the internal details, i.e.,
representing only the essential details in the program.
- Data Abstraction is a programming technique that depends on the
seperation of the interface and implementation details of the
program.
- Let's take a real life example of AC, which can be turned ON or OFF,
change the temperature, change the mode, and other external
components such as fan, swing. But, we don't know the internal
details of the AC, i.e., how it works internally. Thus, we can say that
AC seperates the implementation details from the external
interface.
- C++ provides a great level of abstraction. For example, pow()
function is used to calculate the power of a number without knowing
the algorithm the function follows.
- Data Abstraction is a process of providing only the essential details
to the outside world and hiding the internal details, i.e.,
representing only the essential details in the program.
- Data Abstraction is a programming technique that depends on the
seperation of the interface and implementation details of the
program.
- Let's take a real life example of AC, which can be turned ON or OFF,
change the temperature, change the mode, and other external
components such as fan, swing. But, we don't know the internal
details of the AC, i.e., how it works internally. Thus, we can say that
AC seperates the implementation details from the external
interface.

C++ provides a great level of abstraction. For example, pow() function


is used to calculate the power of a number without knowing the
algorithm the function follows.

Data Abstraction can be achieved in two ways:

o Abstraction using classes


o Abstraction in header files.

Abstraction using classes:

An abstraction can be achieved using classes. A class is used to group all the
data members and member functions into a single unit by using the access
specifiers. A class has the responsibility to determine which data member is to
be visible outside and which is not.
Abstraction in header files:

An another type of abstraction is header file. For example, pow() function


available is used to calculate the power of a number without actually
knowing which algorithm function uses to calculate the power. Thus, we
can say that header files hides all the implementation details from the
user.

Access Specifiers Implement Abstraction:

o Public specifier: When the members are declared as public,


members can be accessed anywhere from the program.
o Private specifier: When the members are declared as private,
members can only be accessed only by the member functions of the
class.

Let's see a simple example of abstraction in header files.

// program to calculate the power of a number.

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
cout << "Cube of n is : " <<result<< endl;
return 0;
}
Output:

Cube of n is : 64
In the above example, pow() function is used to calculate 4 raised to the
power 3. The pow() function is present in the math.h header file in which
all the implementation details of the pow() function is hidden.

Let's see a simple example of data abstraction using classes.

#include <iostream>
using namespace std;
class Sum
{
private:
int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}
Output:

Enter two numbers:


3
6
Sum of two number is: 9
In the above example, abstraction is achieved using classes. A class 'Sum'
contains the private members x, y and z are only accessible by the
member functions of the class.

Advantages Of Abstraction:
o Implementation details of the class are protected from the
inadvertent user level errors.
o A programmer does not need to write the low level code.
o Data Abstraction avoids the code duplication, i.e., programmer does
not have to undergo the same tasks every time to perform the
similar operation.
o The main aim of the data abstraction is to reuse the code and the
proper partitioning of the code across the classes.
o Internal implementation can be changed without affecting the user
level code.

Data Abstraction & ADT


In this topic, you'll learn about abstract data types (ADTs), how they
are used to support data abstraction, and how to create an ADT in
C++. You'll also be able view working code examples.

- When you start your car, you don't need to know the intricate
workings of the starter motor. All you need to do is turn the key to
initiate the sequence.
- If successful, the engine will turn over. This real-world example
highlights the programming concept of data abstraction, which
allows a programmer to protect/hide the implementation of a
process and only gives the keys to other functions or users.
- You only need to know enough about a given function to run it but
don't need to know (or care) about how the internal code works.

To take this a step further, we can create entire data types.

- An abstract data type (or ADT) is a class that has a defined set of
operations and values.
- In other words, you can create the starter motor as an entire
abstract data type, protecting all of the inner code from the user.
When the user wants to start the car, they can just execute the
start() function.
- In programming, an ADT has the following features:

● An ADT doesn't state how data is organized, and


● It provides only what's needed to execute its operations

- An ADT is a prime example of how you can make full use of data
abstraction and data hiding.
- This means that an abstract data type is a huge component of
object-oriented programming methodologies: enforcing abstraction,
allowing data and encapsulation.

One of the most common ADTs is the stack. Let's take a look at it in
action.

Stack Data Type Example

- In this example, we're creating an object-oriented C++ program


that creates an abstract data type in the form of a stack, in which
items can be pushed onto the top and popped off the top.
- The program simulates your browsing history. Each page you visit is
stored in a stack. As you click 'back' on the browser, you are
removing/viewing the top element of the stack. As you go forward
you are pushing them back onto the stack.

This example also shows a little different method for declaring


functions from a class. Notice how they're declared inside the class but
created outside of it. Stacks are very common, so let's see how they
can work for us.

#include <iostream>

using namespace std;

//limit size of browser stack to 100

#define MAX_SIZE 100

class Stack {

public:

int top;

int size[MAX_SIZE];

//constructor

Stack() {

//no top yet

top = -1;

//function declarations

bool push(int page);

int pop();

bool is_empty();
};

//Functions created below

//are we empty?

bool Stack::is_empty() {

return (top < 0);

//pop from stack (back button)

int Stack::pop() {

if(top < 0) {

cout << "Nothing here...";

return 0;

} else {

int page = size[top--];

return page;

//push onto stack

bool Stack::push(int page) {

if(top >= MAX_SIZE) {

cout << "Can't anymore, Jim";

return false;

} else {

size[++top] = page;
return true;

//Finally, create the main function to create a new instance of the


//stack, which you can see appearing here:

int main( ) {

//new stack

Stack pages;

pages.push(5);

pages.push(10);

pages.push(15);

pages.push(20);

cout << " Page " << pages.pop() << " popped from stack " << endl;

cout << " Page " << pages.pop() << " popped from stack " << endl;

return 0;

Output:

Page 20 popped from stack

Page 15 popped from stack

Describing Objects Using ADTs

_ An abstract data type (ADT) is a set of objects and an associated set


of operations on those objects

_ Common examples of ADTs:

User-defined types: stacks, queues, trees, lists


- stack

Values: Stack elements

Operations: create, dispose, push, pop, is_empty, is_full, etc.

-queue

Values: Queue elements

Operations: create, dispose, enqueue, dequeue, is_empty, is_full, etc.

-tree search structure

Values: Tree elements.

Operations: insert, delete, find, size, traverse (in-order, post-order,


pre-order,level-order), etc.

Information Hiding:

In above ADT Stack, we can achieve information hiding by declaring


data members top & size[MAX_SIZE] as private.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy