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

Chapter7 8 9

This document covers fundamental concepts of C++ programming, including pointers, classes, objects, inheritance, polymorphism, and file handling. It explains how to declare pointers, initialize them, and the significance of access specifiers in classes. Additionally, it discusses file handling operations such as opening, reading, and writing files, along with examples to illustrate these concepts.

Uploaded by

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

Chapter7 8 9

This document covers fundamental concepts of C++ programming, including pointers, classes, objects, inheritance, polymorphism, and file handling. It explains how to declare pointers, initialize them, and the significance of access specifiers in classes. Additionally, it discusses file handling operations such as opening, reading, and writing files, along with examples to illustrate these concepts.

Uploaded by

aftabmujeeb786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

CHAPTER: 7

POINTERS
Pointers:are the variables which are used to hold the memory address of the other variable.

Q. How to declare a pointer?

We can declare pointer like:

int*a;

int*ptr;

float*b;

 For the declaration of pointer asterisk (*) symbol is used.


Reference operators or address operators:
Address operator:
 It is denoted by ampersand (&) sign.
 It provides address of memory location.
Example:
int a=25;
int*ptr;

ptr=&a;
cout<<ptr;
it will show the address of a

De-reference operator(*):

If we want to store the values of the variable through the pointer then we will use a special
type of operator calledde-reference operator denoted by(*).

Example:

#include<iostream>

main()

{
int a;
a=10;
int*ptr;

1
p=&a;
cout<<p; //it will show the address of a.
cout<<*p; //it will show the value of a.
}

Declaring variable of pointer types:

 To declare a pointer variable is simple & similar to the declaration of simple variable with a
minor difference of theuse of (*).

Void pointer:

 As we know that a pointer of type int can only points to a variable of type int.It cannot point
to some other data type variable so the data type of the variable & data type of the pointer will be
same, but there isthe special type of pointer calledvoid pointerwhich can point to any data type.
 Its declaration is similar to a normal pointer with the only difference of using a keyword
void.

Syntax:

void*ptr;

Example:

#include<iostream>
main()
{
int x;
float y;
void*ptr;
ptr=&x;
ptr=&y;
}

2
Q. What is pointer initialization? Explain the concept with simple program.
Pointer initialization:

 Assigning values to a pointer at declaration time is called pointer initialization.


 As we know that values of pointers are the address of other variables.
Example:
float temp;
float*ptr=&temp
 In the above e.g.temp is a float variable&*ptris a pointer variable of floating type & the
statementfloat*ptr=&temp;describethepointer initialization.
 The behavior of the above code is equivalent to the following code:
float temp;
float*ptr;
ptr=&temp;

3
CHAPTER: 8
OBJECTS AND CLASSES

Q. What is class & objects?

Class:

 The classes are the most important features of C++.


 Class is user defined data type.
 It is a main feature of oops (object-oriented program).
 It has its own data members & member function.
 The variable inside the class are datamembers.
 The function declare inside the class are called member function.
 Format:
classclass name
{
accessspecifier:
member 1; //data member;
accessspecifier:
member 2; //member function;
};
 Example:
class room
{
private:
int door;
int windows;
public:
my room();
};

4
Q. What is member of Classes?
Class has 2 members
i. Data members
ii. Member functions

i. Data members:
 The variable inside the class are datamembers. We can also say that attributes of class are
called data members.
 Mostly data members are declare under the private access specifier.
 It can also be used under public access specifier.
 The following line of code explain the data members:

class car
{
private:
int door;
int wheel;
};

ii. Member function:


 The function declare inside the class are called member function.
 These member function are mostly written in the public access specifier.
 We can also make the member function by written under the private access specifier.
 Example:
class car
{
private:
int door;
public:
mycar()
{
cout<<"I am in class car";
}
};
main()
{
car c1;
c1.mycar();
}

5
Q. What is access specifier? Explain public & private specifier with example.

Access specifier:

 Access specifier in C++ defines how the members of class can be access.
 They determines that which member of class is accessible in which part of program or class.
 The most commonly used access specifier in C++ are:
i. Private access specifier
ii. Public access specifier

i. Private access specifier:


 They tells the compiler that the member define in the class are accessible only within the
class & its friend function.
 Private members are not accessible outside the class.
 Example:
class temp
{
private:
int x;
public:
show()
{
x=10;
cout<<x;
}
};
main()
{
temp t;
t.show(); //it can access the value of x.
t.x=10; //it cannot access the value of x.
}

6
ii. Public access specifier:
 Public members are accessible accessible from anywhere, within the class, derive class &
main function.
 Example:
class temp
{
public:
int x=10;
public:
show()
{
cout<<x;
}
};
main()
{
temp t;
t.show();
}

Q. What is data hiding/encapsulation? Explain it.


Data hiding:
 Data hiding is one of C++ feature in which member of classes are protected against illegal
access from outside the class.
 In C++ we have the facility of Data hiding using different access level.
i. Private
ii. Public
iii. Protected
 It is also called encapsulation.
 Private data members & member functions can only be accessed within the class & cannot
be accessed outside the class.
 Similarly, in protected data members & members in class can only be accessed within the
class & its derived classes.
 By using friend function, private & unprotected data members & member function of a class
can be accessed.

7
 The following table will show the level of hiding the members of classes.

ACCESS PUBLIC PRIVATE PROTECTED


Access members in
the same class. YES YES YES
Access members in
the derived class. YES NO YES
Access members from
outside class. YES NO NO

Q. What is meant by constructor & destructor? Explain with example.


Constructor:
 It is a special type of member function that initializes an object automatically when it is
created.
 It has the same name as that of the class.
 It has no return type (not even void).
 It is always public.
 Example:

class student
{
public:
student()
{
cout<<"I am in constructor";
}
public:
show()
{
cout<<"I am in show function";
}
};
main ()
{
Studentstd;
}

Constructor overloading:

8
 Using more than one constructor in the same class is called constructor overloading.
 Example:
class temp
{
public:
temp()
{
cout<<"I am in temp constructor1";
}
public:
temp(int a)
{
cout<<"value is"<<a;
}
};
main()
{
temp t1,t2(20);
}

Destructors:
 They are special member functions that are executed when an object is destroyed.
 They are called automatically when objects are destroyed.
 They are denoted by (~) tilde sign.
 Features:
i. They have same name as that of class name preceded by(~)tilde symbol.
ii. They cannot take arguments.
iii. It has no return type.

Basically it de-allocates the memory allocated to an object during its creation.

 Example:
class student
{
public:
student()
{
cout<<"I am in constructor";
}
public: ~student()

9
{
cout<<"I am in destructor";
}
};
main()
{
studentstd;
}

Q. Write a program which performs addition of 3 numbers by using classes.

#include<iostream>
using namespace std;
{
class my class
{
private:
inta,b,c,sum;
public:
sumfun();
{
cin>>a>>b>>c;
sum=a+b+c;
cout<<"the sum is="<<sum;
}
};
main()
{

my classc1

c1.sumfun();

}
}

Q. Explain inheritance & polymorphism with examples?

10
Object oriented programming languages have a key features inheritance & polymorphism.

Inheritance:

 When new classes are created from existing classes is called inheritance.
 It use the concept of parent & child class.
 A (parent class) is a class from which other classes are derived.
 It is also called base class.
 A sub-class is a class which inherit features from base class
 It is also called child class or derived class.
 Example:
#include<iostream>
using namespace std;
{
class A
{
public:
show a()
{
cout<<"I am in base class A ";
}
};
class B: public A
{
public:
show b()
{
cout<<"I am in child class";
}
};
main()
{
B b1;
b1.show a();
b1.show b();
}
}

Polymorphism:
 It is the ability to use an operator or function in multiple ways.

11
 It gives different meanings to the operators or function.
 Example:
A person can be a student & a friend to another person.
 In C++ it can be achieve by one of the following concept:
i. Functions overloading
ii. Operators overloading
iii. Virtual function

ii. Operators overloading:


 Consider the following e.g. to understand the concept of operator overloading.
6+10
 The above statement refer to integer addition with the help of plus(+)operator.
 The same(+)operator can also be used for addition of floating points.
7.5+8.3
 The same(+)operator can also be used for 2 strings (concatenation).
“hello”+“world”
 So that a single operator (+)behave differently in different situations/context such as
integers, floating & string concatenation.
 This is also known as operators overloading.

Virtual Function:
 It is a function whose behavior can be overridden within a inheriting class by a function with
same signature.
 This concept is very important part of polymorphism in object oriented programming.

Chapter No .9
File Handling in C++
What is file?

12
A file is a collection of bytes stored on storage device like hard disk.

For example: Characters, Words, Lines, and Paragraphs etc.

What is meant by file handling? Explain different types of files.

File handling concept in C++ language is use for storing data permanently in computer.

It provides a mechanism to write output of a program into a file and from a file.

The basic operations involved in file handling are:

(i) Opening a file.


(ii) Reading and writing a file.
(iii) Closing file.

TYPES OF FILES
C++ divides files into two different types based on how they store data.

1. Text files.
2. Binary files.

TEXT FILE:

1. Text files are the stream of characters that computer can process sequentially.
2. It is not only processed sequentially but also in forward direction.
3. For this reason, text files are usually opened for only one kind of operation (reading, writing,
appending) at any given time.
4. Similarly, text files only process characters they can only read and write data one character
at a time.
5. In C++ programming language, functions are provided that deal with the lines of text.

BINARY FILES:

1. Binary file is the collection of bytes.


2. In C++ programming language, byte and character are equivalent.
3. Hence a binary file is also referred to as a character stream but there are two differences.
(i) No special processing of data occurs and each byte of data is transferred to or from
the disk unprocessed.
(ii) C programming language plays no construct on the file or it maybe read or written in
any manner.
(iii) 4 Binary files can either be processed sequentially or they can be processed using
random access techniques.

13
In C++ programming language, processing a file using random access techniques involves moving
the current file position to an appropriate file before reading and writing data.For example,
database files will be created and processed as a binary file.

OPENING A FILE:

To open a file we use a function open ().

The syntax will be:

myfile.open(filename);

Here myfileis a variable which handle the file whose name is written in parenthesis.

Ifstreammyfile;

It is use to declare variable or we can say to declare variable myfilewe use the following statement.

The dot operator is used between the variable myfile and open function.

The file name can be a “sale.txt”.

MODES OF OPENING A FILE:

While opening a file we tell the computer what we want to do with the file.

i) We want to read the file.


ii) We want to write the file.
iii) We want to modify the file.

In order to open a file in any desire of mode the function arguments along with the file name.

Its general syntax will be:

Open (filename. Mode);

Here file name representing of the file to be open and mode is an optional parameter with the
combination of following flags:

MODE DESCRIPTION
ios::in Open for input operation (reading a file).
ios::out Open for output operation (writing a file).
ios::binary Open in binary mode.
ios::ate Open a file for output and move the read/write control to the end of the

14
file.
ios::app Append mode. All output to that file to be appended to the end.

ios::trunc If the file opened for output operations, its existing contents are deleted
and replaced by new one.

CLASS MODE
ofstream ios::out
ifstream ios::in
fstream ios::in/ios::out

For ifstream and ofstream classes ios::in and ios::out are automatically and respectively
assumed, even if modes that does not include them is passed as second argument to open
function.

Write a program which create a file example.txt and write a line of text in it.

#include<iostream>
#include<fstream>
using namespace std;

main()

ofstream myfile;

myfile.open(“example.txt”);

myfile<<”welcome to file handling”;

myfile.close();

Explanation:

This code create a file called”example.txt” and write a sentence “welcome to file handling” in it

It shows the output of above program in form of text file created in a same working directory.

15
READING THE FILE:

To read a word from the file, we can write as myfile>>c;So the first word of the file will be read in c,
where c is a character array.

It is similar as we used in Cin>>.

There are certain limitations to this:

(i)It can read just one character/letter at one time.

(ii) It means that when a space will come, it will stop reading further.

Therefore we have to use it repeatedly to read the complete file.

We can also read multiple character at a time myfile>>c1>>c2>>c3;

The first character will be read in c1, second in c2 and the third in c3.

Write a program that input file example.txt which read and display the text on screen?

#include<iostream>
#include<fstream>
using namespace std;

main()
{
Ifstream myfile;
Char ch[100];
myfile.open(“example.txt”);

myfile>>ch;

cout<<ch;

myfile.close();

Explain bof() function and eof() function?

C++ provides a special function bof() and eof().

bof() function:

16
1) bof stands for beginning of file.
2) It is used to set the pointer at the beginning of the file.
3) It returns true if the current position of a pointer is at the beginning of a file otherwise it
returns false.
4) It means that it tells the compiler whether the cursor is at the beginning of file or not.

eof() function:

1) eof means that end of file.


2) It is used to set the pointer at the end of file.
3) It returns true when there are no more data to be read from file otherwise it returns
false.
4) It means that this function checks whether the control reach to the end of file or not.
5) This function is very useful in the case when we do not know the exact number of
records in a file.

RULES FOR USING eof():


 Always test for end-of-file condition before processing data.
 Use a while loop for getting data from an input file.(stream)

Q Write a program which reads data from a file by using eof() function?

#include<iostream>

#include<fstream>

17
using namespace std;

main()

Ifstream myfile;

charch[100];

myfile.open(“example.txt”);

While(! myfile.eof())

myfile>>ch;

cout<<ch<<endl;

myfile.close();

Q:what is stream? Describe input/output stream in detail.

In C++ stream is a sequence of bytes associated with file.

In C++ there are two types of streams:

1)Input stream

2) Output stream

Input stream
Input stream takes any sequence of bytes from an input device such as keyboard,
file, and network.

Output stream
Output streams are used to hold output for a particular data consumer such as
moniter, printer etc.

18
Reading and writing in a file:

1) If he is only used for reading purpose then header file “if stream” is used (input file
stream stream).
2) Similarly, if we want to write some file then header file “of stream” (output file stream)
is used.
3) One can reads, writes,manipulate the same file by using header file “f stream”.
Types of stream
The data can be read from and return to files with the help of following streams:
i) Single character stream
ii) String stream

Single character stream

1) Using single character stream the data can be read from and written to files character by
character.
2) The function get() is used to read data character by character.

Q: write a program which reads the data one character at a time from the file “example.txt”?

#include<iostream>
#include<fstream>
using namespace std;
main()
{
charch;
ifstream myfile(“example.txt”);

while(!myfile.eof())
{
myfile.get(ch);
cout<<ch;
}
myfile.close();
}

Writing file character by character:


19
1) Similarly, using single character stream data can be written to files character by
character by using the functions put().
2) Now program can also writes data character by character in the file.

Program:
#include<iostream>
#include<fstream>
using namespace std;
main()
{
charch;
int a;
ofstream myfile(“example.txt”);
for (a=1;a<=20;a++)
{
cin>>ch;
cout<<myfile.put(ch);
}
myfile.close();
}
String stream:
1) A string stream is a stream which reads input from or writes output to an associated
stream.
2) Now consider the following txt file “mystring.txt” which reads the file by using get line
function and display the result on screen.
Program:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
main()
{
charch[20];
ifstreammyfile(“example.txt”);

while (!myfile.eof())
{
myfile.getline(ch,20);
cout<<ch;
}
myfile.close(); }

20

You might also like