c notes for beginners

55
1. Can we declare a static function as virtual? Ans: No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual. !. Can userdefined object be declared as static data member of another class? Ans: "es. The followin# code shows how to initiali$e a userdefined object. %include class test  & int i ' public : test ( int ii ) * + & i ) ii ' '  class sample  & static test s ' '  test sample::s ( !- + ' ere we have initiali$ed the object s by callin# the onear#ument constructor. /e can use the same convention to initiali$e the object by callin# multiplear#ument constructor. 0. /hat is forward referencin# and when should it be used? Ans: Consider the followin# pro#ram: class test  & public : friend void fun ( sample, test + ' '  class sample

Upload: abhinandangour

Post on 04-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 1/55

1.

Can we declare a static function as virtual?

Ans: No. The virtual function mechanism is used on the specific object that

determines which virtual function to call. Since the static functions are not any wayrelated to objects, they cannot be declared as virtual.

!.

Can userdefined object be declared as static data member of another class?

Ans: "es. The followin# code shows how to initiali$e a userdefined object.

%include

class test  &

int i 'public :

test ( int ii ) * +&

i ) ii '

'

  class sample  &

static test s '

'  test sample::s ( !- + '

ere we have initiali$ed the object s by callin# the onear#ument constructor. /ecan use the same convention to initiali$e the object by callin# multiplear#ument

constructor.

0.

/hat is forward referencin# and when should it be used?

Ans: Consider the followin# pro#ram:

class test

  &public :

friend void fun ( sample, test + ' '

  class sample

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 2/55

  &public :

friend void fun ( sample, test + ' '

  void fun ( sample s, test t +

  & 11 code

  void main( +  &

sample s '  test t '

  fun ( s, t + '

This pro#ram would not compile. 2t #ives an error that sample is undeclared identifierin the statement friend void fun ( sample, test + ' of the class test. This is so because

the class sample is defined below the class test and we are usin# it

before its definition. To overcome this error we need to #ive forward reference ofthe class sample before the definition of class test. The followin#

statement is the forward reference of class sample. 3orward

referencin# is #enerally re4uired when we ma5e a class or a function as a friend.

6.

The istream7withassi#n class has been derived from the istream class and

overloaded assi#nment operator has been added to it. The 7withassi#n classes are much li5e their base classes e8cept that

they include overloaded assi#nment operators. 9sin# these operators the objects of

the 7withassi#n classes can be copied. The istream, ostream,and iostream classes are made uncopyable by ma5in# their

overloaded copy constructor and assi#nment operators private.

.

ow do 2 write my own $eroar#ument manipulator that should wor5 same as he8?

Ans: This is shown in followin# pro#ram.

%include

ostream; myhe8 ( ostream ;o +&

o.setf ( ios::he8+ '

return o '

void main( +

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 3/55

&

cout << endl << myhe8 << !*** '

-.

/e all 5now that a const variable needs to be initiali$ed at the time of declaration.Then how come the pro#ram #iven below runs properly even when we have not

initiali$ed p?

  %includevoid main( +

  &  const char =p '

  p ) >A const pointer> '

  cout << p '   

Ans: The output of the above pro#ram is A const pointer. This is because in thispro#ram p is declared as const char= which means that value stored at p will be

constant and not p and so the pro#ram wor5s properly@.

ow do 2 refer to a name of class or function that is defined within a namespace?

Ans: There are two ways in which we can refer to a name of class or function that is

defined within a namespace: 9sin# scope resolution operator

throu#h the usin# 5eyword. This is shown in followin# e8ample:namespace name

  &class sample

  & 11 code

'

  namespace name!

  &class sample!

  & 11 code

'

usin# namespace name! '  void main( +

  &name::sample s '

  sample! s! '

ere, class sample is referred usin# the scope resolution operator. Bn the other

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 4/55

hand we can directly refer to class sample! because of thestatement usin# namespace name! ' the usin# 5eyword declares all the names in

the namespace to be in the current scope. So we can use the names without any4ualifiers.

.

/hile overloadin# a binary operator can we provide default values?

Ans: NoD. This is because even if we provide the default ar#uments to the

parameters of the overloaded operator function we would endup usin# the binary operator incorrectly. This is e8plained in the

followin# e8ample:sample operator E ( sample a, sample b ) sample (!, 0.f + +

  & 

  void main( +  &

sample s, s!, s0 '

  s0 ) s E ' 11 error

F.

ow do 2 carry out conversion of one object of userdefined type to another?

Ans: To perform conversion from one userdefined type to another we need to

provide conversion function. 3ollowin# pro#ram demonstrateshow to provide such conversion function.

class circle  &

private :int radius '

public:

circle ( int r ) * +  &

radius ) r '

'class rectan#le

  &private :

int len#th, breadth 'public :

rectan#le( int l, int b +  &

len#th ) l '  breadth ) b '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 5/55

  operator circle( +  &

return circle ( len#th + '

'  void main( +

  &rectan#le r ( !*, * + '

  circle c'

  c ) r '

ere, when the statement c ) r ' is e8ecuted the compiler searches for an

overloaded assi#nment operator in the class circle which acceptsthe object of type rectan#le. Since there is no such overloaded

assi#nment operator, the conversion operator function that converts the rectan#leobject to the circle object is searched in the rectan#le class. /e

have provided such a conversion function in the rectan#le class.This conversion operator function returns a circle object. Gy

default conversion operators have the name and return type same as the object type

to which it converts to. ere the type of the object is circle andhence the name of the operator function as well as the returntype is circle.

*.ow do 2 write code that allows to create only one instance of a class?

Ans: This is shown in followin# code snippet.

%include

class sample

&static sample =ptr '

private:sample( +

  & 

public:

static sample= create( +  &

if ( ptr )) N9HH +ptr ) new sample '

return ptr '

'  sample =sample::ptr ) N9HH '

  void main( +  &

sample =a ) sample::create( + '  sample =b ) sample::create( + '

ere, the class sample contains a static data member ptr, which is a pointer to the

object of same class. The constructor is private which avoids us

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 6/55

from creatin# objects outside the class. A static memberfunction called create( + is used to create an object of the class. 2n this function

the condition is chec5ed whether or not ptr is N9HH, if it is then anobject is created dynamically and its address collected in ptr is

returned. 2f ptr is not N9HH, then the same address is returned.Thus, in main( + on e8ecution of the first statement one object of sample #ets

created whereas on e8ecution of second statement, b holds theaddress of the first object. Thus, whatever number of times you call create( +function, only one object of sample class will be available.

.

ow do 2 write code to add functions, which would wor5 as #et and put properties of

a class?

Ans: This is shown in followin# code.%include

class sample&int data '

public: 77declspec ( property ( put ) fun, #et ) fun! + +

int 8 '  void fun ( int i +

  &if ( i < * +

data ) * 'else

data ) i '

  int fun!( +

  &return data '

'

  void main( +  &

sample a '  a.8 ) FF '

  cout << a.8 '

ere, the function fun( + of class sample is used to set the #iven inte#er value intodata, whereas fun!( + returns the current value of data. To set

these functions as properties of a class we have #iven thestatement as shown below:

 77declspec ( property ( put ) fun, #et ) fun! ++ int 8 'As a result, the statement a.8 ) FF ' would cause fun( + to #et called to set the

value in data. Bn the other hand, the last statement wouldcause fun!( + to #et called to return the value of data.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 7/55

!.

ow do 2 write code to ma5e an object wor5 li5e a !I array?

Ans: Ta5e a loo5 at the followin# pro#ram.

%includeclass emp

  &

public :int aJ0KJ0K '

emp( +  &

int c ) 'for ( int i ) * ' i <) ! ' iEE +

  &for ( int j ) * ' j <) ! ' jEE +

  &

aJiKJjK ) c '  cEE '

  int= operatorJK ( int i +

  &return aJiK '

'

  void main( +  &

emp e '  cout << eJ*KJK '

The class emp has an overloaded operator J K function. 2t ta5es one ar#ument an

inte#er representin# an array inde8 and returns an int pointer.

The statement cout << eJ*KJK ' would #et converted into a callto the overloaded J K function as e.operatorJ K ( * +. * would #et

collected in i. The function would return aJiK that represents the base address of the$eroeth row. Ne8t the statement would #et e8panded as base

address of $eroeth rowJK that can be further e8panded as=( base address E +. This #ives us a value in $eroth row and first column.

0.

/hat are formattin# fla#s in ios class?

Ans: The ios class contains formattin# fla#s that help users to format the streamdata. 3ormattin# fla#s are a set of enum definitions. There are

two types of formattin# fla#s:Bn1Bff fla#s

3la#s that wor5 in#roup

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 8/55

The Bn1Bff fla#s are turned on usin# the setf( + function and are turned off usin# theunsetf( + function. To set the Bn1Bff fla#s, the one ar#ument

setf( + function is used. The fla#s wor5in# in #roups are setthrou#h the twoar#ument setf( + function. 3or e8ample, to left justify a

strin# we can set the fla# as,cout.setf ( ios::left + '

  cout << >L2C2T Na#pur> 'To remove the left justification for subse4uent output we can say,

cout.unsetf ( ios::left + '

The fla#s that can be set1unset include s5ipws, showbase, showpoint, uppercase,

showpos, unitbuf and stdio. The fla#s that wor5 in a #roup canhave only one of these fla#s set at a time.

6./hat is the purpose of ios::basefield in the followin# statement?

cout.setf ( ios::he8, ios::basefield + 'Ans: This is an e8ample of formattin# fla#s that wor5 in a #roup. There is a fla# foreach numberin# system (base+ li5e decimal, octal and

he8adecimal. Collectively, these fla#s are referred to asbasefield and are specified by ios::basefield fla#. /e can have only one of these

fla#s on at a time. 2f we set the he8 fla# as setf ( ios::he8 + then wewill set the he8 bit but we wont clear the dec bit resultin# in

undefined behavior. The solution is to call setf( + as setf( ios::he8, ios::basefield +. This call first clears all the bits and then sets the he8 bit.

.

Can we #et the value of ios format fla#s?

  Ans: "esD The ios::fla#s( + member function #ives the value format fla#s. Thisfunction ta5es no ar#uments and returns a lon# ( typedefed to

fmtfla#s+ that contains the current format fla#s.

-.

2s there any function that can s5ip certain number of characters present in the inputstream?

Ans: "esD This can be done usin# cin::i#nore( + function. The prototype of this

function is as shown below:  istream; i#nore ( int n ) , int d )MB3 + '

Sometimes it happens that some e8tra characters are left in the input stream whileta5in# the input such as, the n (Mnter+ character. This e8tra

character is then passed to the ne8t input and may poseproblem.

To #et rid of such e8tra characters the cin::i#nore( + function is used. This is

e4uivalent to fflush ( stdin + used in C lan#ua#e. This function i#nores the first n

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 9/55

characters (if present+ in the input stream, stops if delimiter d is encountered.

@.

/rite a pro#ram that implements a date class containin# day, month and year asdata members. 2mplement assi#nment operator and copyconstructor in this class.

Ans: This is shown in followin# pro#ram:%include

class date

  &private :

int day '  int month '

  int year '

public :date ( int d ) *, int m ) *, int y ) * +&

day ) d '  month ) m '

  year ) y '

  11 copy constructor

  date ( date ;d +&

day ) d.day '

  month ) d.month '  year ) d.year '

  11 an overloaded assi#nment operator  date operator ) ( date d +

&

day ) d.day '  month ) d.month '

  year ) d.year 'return d '

void display( +

  &cout << day << >1> << month << >1> << year '

'

  void main( +

  &date d ( !, F, F@F + '

  date d! ) d '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 10/55

  date d0 '  d0 ) d! '

d0.display( + '

.

/hen should 2 use unitbuf fla#?

Ans: The unit bufferin# (unitbuf+ fla# should be turned on when we want to ensure

that each character is output as soon as it is inserted into an

output stream. The same can be done usin# unbuffered outputbut unit bufferin# provides a better performance than the unbuffered output.

F.

/hat are manipulators?Ans: Oanipulators are the instructions to the output stream to modify the output in

various ways. The manipulators provide a clean and easy way

for formatted output in comparison to the formattin# fla#s of theios class. /hen manipulators are used, the formattin# instructions

are inserted directly into the stream. Oanipulators are of two types, those that

ta5e an ar#ument and those that dont.

!*.

/hat is the difference between the manipulator and setf( + function?

Ans: The difference between the manipulator and setf( + function are as follows:

The setf( + function is used to set the fla#s of the ios but manipulators directly insert

the formattin# instructions into the stream. /e can createuserdefined manipulators but setf( + function uses data

members of ios class only. The fla#s put on throu#h the setf( + functioncan be put off throu#h unsetf( + function. Such fle8ibility is not available with

manipulators.

!.ow do 2 #et the current position of the file pointer?

Ans: /e can #et the current position of the file pointer by usin# the tellp( + memberfunction of ostream class or tell#( + member function of istream class. These

functions return (in bytes+ positions of put pointer and #etpointer respectively.

!!./hat are put and #et pointers?

Ans: These are the lon# inte#ers associated with the streams. The value present in

the put pointer specifies the byte number in the file from wherene8t write would ta5e place in the file. The #et pointer specifies

the byte number in the file from where the ne8t readin# should ta5e place.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 11/55

!0./hat do the nocreate and noreplace fla# ensure when they are used for openin# a

file?

Ans: nocreate and noreplace are fileopenin# modes. A bit in the ios class definesthese modes. The fla# nocreate ensures that the file must e8istbefore openin# it. Bn the other hand the fla# noreplace ensures

that while openin# a file for output it does not #et overwritten with new one

unless ate or app is set. /hen the app fla# is set then whatever we write#ets appended to the e8istin# file. /hen ate fla# is set we can

start readin# or writin# at the end of e8istin# file.

!6.

/hat is the limitation of cin while ta5in# input for character array?

Ans: To understand this consider followin# statements,

char strJK '  cin PP str '/hile enterin# the value for str if we enter more than characters then there is no

provision in cin to chec5 the array bounds. 2f the arrayoverflows, it may be dan#erous. This can be avoided by usin#

#et( + function. 3or e8ample, consider followin# statement,cin.#et ( str, + '

Bn e8ecutin# this statement if we enter more than characters, then #et( + ta5es

only first five characters and i#nores rest of the characters.Some more variations of #et( + are available, such as shown

below:

  #et ( ch + M8tracts one character only

  #et ( str, n + M8tracts up to n characters into str

  #et ( str, IMH2O + M8tracts characters into array str until

specified delimiter (such as n+. Heaves delimitin# character in

stream.

  #et ( str, n, IMH2O + M8tracts characters into array str until ncharacters or IMH2O character, leavin# delimitin# character in stream.

!.

/hat is the purpose of istream class?

Ans: The istream class performs activities specific to input. 2t is derived from the iosclass. The most commonly used member function of this class is

the overloaded PP operator which can e8tract values of all basictypes. /e can e8tract even a strin# usin# this operator.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 12/55

!-.

/ould the followin# code wor5?

%includevoid main( +

  &ostream o '

  o << >Iream. Then ma5e it happenD> '

Ans: NoD This is because we cannot create an object of the ostream class since itsconstructor and copy constructor are declared private.

!@.

Can we use this pointer inside static member function?

Ans: NoD The this pointer cannot be used inside a static member function. This isbecause a static member function is never called throu#h an

object.

!.

/hat is strstream?

Ans: strstream is a type of input1output stream that wor5s with the memory. 2tallows usin# section of the memory as a stream object. These

streams provide the classes that can be used for storin# thestream of bytes into memory. 3or e8ample, we can store inte#ers, floats and strin#s

as a stream of bytes. There are several classes that implementthis inmemory formattin#. The class ostrstream derived from ostream is used when

output is to be sent to memory, the class istrstream derived from istream is used

when input is ta5en from memory and strstream class derived from iostream is usedfor

memory objects that do both input and output.

!F.

Ans: /hen we want to retrieve the streams of bytes from memory we can use

istrestream. The followin# e8ample shows the use of istrstreamclass.

%include

void main( +  &

int a#e '  float salary '

  char nameJ*K '  char strJK ) >!! !**6.* L. Qishwanatth> '

  istrstream s ( str + '

  s PP a#e PP salary PP name '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 13/55

  cout << a#e << endl << salary << endl << name '

  cout << endl << s.rdbuf( + '

ere, s is the object of the class istrstream. /hen we are creatin# the object s, theconstructor of istrstream #ets called that receives a pointer to

the $ero terminated character array str. The statement s PPa#e PP salary PP name ' e8tracts the a#e, salary and the name from the istrstream

object s. owever, while e8tractin# the name, only the first

word of name #ets e8tracted. The balance is e8tracted usin#

rdbuf( +.

0*./hen the constructor of a base class calls a virtual function, why doesnt the

override function of the derived class #ets called?

Ans: /hile buildin# an object of a derived class first the constructor of the base class

and then the constructor of the derived class #ets called. Theobject is said an immature object at the sta#e when theconstructor of base class is called. This object will be called a matured object after

the e8ecution of the constructor of the derived class. Thus, if wecall a virtual function when an object is still immature,

obviously, the virtual function of the base class would #et called. This isillustrated in the followin# e8ample.

%include

class base  &

protected :

int i 'public :

base ( int ii ) * +  &

i ) ii '  show( + '

  virtual void show( +

  &cout << >bases show( +> << endl '

'

  class derived : public base

  &private :

int j 'public :

derived ( int ii, int jj ) * + : base ( ii +  &

 j ) jj '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 14/55

  show( + '

void show( +  &

cout << >deriveds show( +> << endl '

'

void main( +

  &

derived dobj ( !*, + '

The output of this pro#ram would be:bases show( +

  deriveds show( +0.

Can 2 have a reference as a data member of a class? 2f yes, then how do 2 initialiseit?

Ans: "es, we can have a reference as a data member of a class. A reference as adata member of a class is initialised in the initialisation list ofthe constructor. This is shown in followin# pro#ram.

%include

class sample  &

private :int; i '

public :sample ( int; ii + : i ( ii +

&

 

  void show( +  &

cout << i << endl '

'

  void main( +

  &int j ) * '

  sample s ( j + '  s.show( + '

ere, i refers to a variable j allocated on the stac5. A point to note here is that we

cannot bind a reference to an object passed to the constructoras a value. 2f we do so, then the reference i would refer to the

function parameter (i.e. parameter ii in the constructor+, which woulddisappear as soon as the function returns, thereby creatin# a situation of

dan#lin# reference.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 15/55

0!./hy does the followin# code fail?

  %include

class sample

  &private :char =str '

public :

sample ( char =s +  &

strcpy ( str, s + '

  Rsample( +

  &delete str '

'

  void main( +

  &sample s ( >abc> + '

Ans: ere, throu#h the destructor we are tryin# to deal locate memory, which has

been allocated statically. To remove an e8ception, add followin#statement to the constructor.

sample ( char =s +  &

str ) new charJstrlen(s+ E K '

  strcpy ( str, s + '

ere, first we have allocated memory of re4uired si$e, which then would #et deallocated throu#h the destructor.

00.

assert( + macro...

/e can use a macro called assert( + to test for conditions that should not occur in acode. This macro e8pands to an if statement. 2f test evaluates

to *, assert prints an error messa#e and calls abort to abort thepro#ram.

%include%include

void main( +

  &int i '

  cout << >nMnter an inte#er: > '

  cin PP i '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 16/55

  assert ( i P) * + '

  cout << i << endl '

06.

/hy it is unsafe to deal locate the memory usin# free( + if it has been allocated usin#new?Ans: This can be e8plained with the followin# e8ample:

%include

class sample

  &int =p '

public :sample( +

  &p ) new int '

  Rsample( +  &

delete p '

'

  void main( +  &

sample =s ) new sample '  free ( s + '

  sample =s! ) ( sample = + malloc ( si$eof ( sample+ + '

  delete s! '

The new operator allocates memory and calls the constructor. 2n the constructor wehave allocated memory on heap, which is pointed to by p. 2f we

release the object usin# the free( + function the object would die but the memory

allocated in the constructor would lea5. This is because free( + bein# a C libraryfunction does not call the destructor where we have deal located the memory.

As a#ainst this, if we allocate memory by callin# malloc( + the constructor would not

#et called. ence p holds a #arba#e address. Now if the memory is deal locatedusin# delete, the destructor would #et called where we have

tried to release the memory pointed to by p. Since p contains #arba#ethis may result in a runtime error.

0.

Can we distribute function templates and class templates in object libraries?

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 17/55

Ans: NoD /e can compile a function template or a class template into object code

(.obj file+. The code that contains a call to the function template or the code thatcreates an object from a class template can #et compiled. This is because the

compiler merely chec5s whether the call matches the declaration (in case of functiontemplate+ and whether the object definition matches class declaration (in case of

class template+. Since the function template and the class template definitions arenot found, the compiler leaves it to the lin5er to restore this. owever, durin#lin5in#, lin5er doesnt find the matchin# definitions for the function call or a matchin#

definition for object creation. 2n short the e8panded versions of templates are not

found inthe object library. ence the lin5er reports error.

0-./hat is the difference between an inspector and a mutator ?

 Ans: An inspector is a member function that returns information about an objects

state (information stored in objects data members+ without chan#in# the objects

state. A mutator is a member function that chan#es the state of an object. 2n theclass Stac5 #iven below we have defined a mutator and an inspector. 

class Stac5  &

  public :  int pop( + '

  int #etcount( + ' 

 2n the above e8ample, the function pop( + removes top element of stac5 thereby

chan#in# the state of an object. So, the function pop( + is a mutator. The function

#etcount( + is an inspector because it simply counts the number of elements in thestac5 without chan#in# the stac5.

0@.

Namespaces:

 

The CEE lan#ua#e provides a sin#le #lobal namespace. This can cause problemswith #lobal name clashes. 3or instance, consider these two CEE header files:

  11 file.h

  float f ( float, int + '  class sample & ... '

  11 file!.h

  class sample & ... ' 

/ith these definitions, it is impossible to use both header files in a sin#le pro#ram'the sample classes will clash.A namespace is a declarative re#ion that attaches an

additional identifier to any names declared inside it. The additional identifier thusavoids the possibility that a name will conflict with names declared elsewhere in the

pro#ram. 2t is possible to use the same name in separate namespaces without

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 18/55

conflict even if the names appear in the same translation unit. As lon# as theyappear in separate namespaces, each name will be uni4ue because of the addition of

the namespace identifier. 3or e8ample: 

 11 file.h  namespace file

  &  float f ( float, int + '  class sample & ... '

 

  11 file!.h

  namespace file!  &

  class sample & ... ' 

 Now the class names will not clash because they become file::sample and

file!::sample, respectively.

0.

/hat would be the output of the followin# pro#ram?

%includeclass user

&int i '

float f 'char c '

public :

void displaydata( +&

cout << endl << i << endl << f << endl << c '

'

void main( +

&cout << si$eof ( user + '

user u 'cout << endl << si$eof ( u + '

u.displaydata( + '

Ans: The output of this pro#ram would be,

F or @

F or @arba#e

arba#earba#e

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 19/55

Since the user class contains three elements, int, float and char its si$e would be Fbytes (int6, float6, char+ under /indows and @ bytes (int!, float6, char+

under IBS. Second output is a#ain the same because u is an object of the classuser. 3inally three #arba#e values are printed out because i, f and c are not

initiali$ed anywhere in the pro#ram.

Note that if you run this pro#ram you may not #et the answer shown here. This isbecause pac5in# is done for an object in memory to increase the access efficiency.3or e8ample, under IBS, the object would be ali#ned on a !byte boundary. As a

result, the si$e of the object would be reported as - bytes. 9nli5e this, /indows

bein# a 0!bit BS the object would be ali#ned on a 6byte boundary. ence the si$eof the object would be reported as ! bytes. To force the ali#nment on a byte

boundary, write the followin# statement before the class declaration.%pra#ma pac5 ( +

0F.

/rite a pro#ram that will convert an inte#er pointer to an inte#er and viceversa.

  Ans: The followin# pro#ram demonstrates this.%include

void main( +  &

int i ) -*** '

  int =iptr ) reinterpret7cast ( i + '  cout << endl << iptr '

iptrEE '

cout << endl << iptr '

  i ) reinterpret7cast ( iptr + '

  cout << endl << i '

iEE 'cout << endl << i '

6*.

/hat is a const7cast?

Ans. The const7cast is used to convert a const to a nonconst. This is shown in thefollowin#

pro#ram:%include

void main( +  &

const int a ) * '  int =ptr ) ( int = + ;a ' 11one way

  ptr ) const7cast7 ( ;a + ' 11better way

ere, the address of the const variable a is assi#ned to the pointer to a nonconst

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 20/55

variable. The const7cast is also used when we want to chan#e the data members ofa class inside the const member functions. The followin# code snippet shows this:

class sample  &

private:int data'

public:void func( + const

  &

(const7cast (this++Pdata ) @* '

'

6./hat is forward referencin# and when should it be used?

Ans: 3orward referencin# is #enerally re4uired when we ma5e a class or a functionas a friend.

Consider followin# pro#ram:

class test  &

public:

friend void fun ( sample, test + ' '

class sample

&public:

friend void fun ( sample, test + ' '

void fun ( sample s, test t +&

 11 code

void main( +

&

sample s 'test t '

fun ( s, t + '

Bn compilin# this pro#ram it #ives error on the followin# statement of test class. 2t#ives an error that sample is undeclared identifier. friend void fun ( sample, test + '

This is so because the class sample is defined below the class test and we are usin#it before its definition. To overcome this error we need to #ive forward reference of

the class sample before the definition of class test. The followin# statement is theforward reference of class sample.

class sample '

6!.

ow would you #ive an alternate name to a namespace?

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 21/55

Ans: An alternate name #iven to namespace is called a namespacealias.

namespacealias is #enerally used to save the typin# effort when the names ofnamespaces are very lon# or comple8. The followin# synta8 is used to #ive an alias

to a namespace.namespace myname ) my7old7very7lon#7name '

60.

9sin# a smart pointer can we iterate throu#h a container?

Ans: "es. A container is a collection of elements or objects. 2t helps to properlyor#ani$e and store the data. Stac5s, lin5ed lists, arrays are e8amples of containers.

3ollowin# pro#ram shows how to iterate throu#h a container usin# a smart pointer.%include

class smartpointer

  &

private :int =p ' 11 ordinary pointerpublic :

smartpointer ( int n +  &

p ) new int J n K '  int =t ) p '

  for ( int i ) * ' i <) F ' iEE +=tEE ) i = i '

  int= operator EE ( int +

  &return pEE '

  int operator = ( +  &

return =p '

'

  void main( +

  &smartpointer sp ( * + '

  for ( int i ) * ' i <) F ' iEE +

cout << =spEE << endl '

ere, sp is a smart pointer. /hen we say =sp, the operator = ( + function #ets called.2t returns the inte#er bein# pointed to by p. /hen we say spEE the operator EE ( +

function #ets called. 2t increments p to point tothe ne8t element in the array and then returns the address of this new location.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 22/55

66.Can objects read and write themselves?

Ans: "esD This can be e8plained with the help of followin# e8ample:

  %include

%include

class employee

  &

private :char name J !* K '

  int a#e '  float salary '

public :void #etdata( +

&cout << >Mnter name, a#e and salary of employee : > '

  cin PP name PP a#e PP salary '

  void store( +

  &ofstream file '

  file.open ( >MOHB"MM.IAT>, ios::app U ios::binary + '  file.write ( ( char = + this, si$eof ( =this + + '

file.close( + '

  void retrieve ( int n +

  &

ifstream file '  file.open ( >MOHB"MM.IAT>, ios::binary + '

  file.see5# ( n = si$eof ( employee + + '  file.read ( ( char = + this, si$eof ( =this + + '

  file.close( + '

  void show( +  &

cout << >Name : > << name  << endl << >A#e : > << a#e

<< endl << >Salary :> << salary << endl '

'

  void main( +  &

employee e J K '

  for ( int i ) * ' i <) 6 ' iEE +&

e J i K.#etdata( + '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 23/55

  e J i K.store( + '

  for ( i ) * ' i <) 6 ' iEE +

&e J i K.retrieve ( i + '

  e J i K.show( + '

ere, employee is the class whose objects can write and read themselves. The

#etdata( + function has been used to #et the data of employee and store it in thedata members name, a#e and salary. The store( + function is used to write an object

to the file. 2n this function a file has been opened in append mode and each timedata of current object has been stored after the last record (if any+ in the

file.3unction retrieve( + is used to #et the data of a particular employee from the file.This retrieved data has been stored in the data members name, a#e and salary. ere

this has been used to store data since it contains the address of the current object.The function show( + has been used to display the data of employee.

6./hy is it necessary to use a reference in the ar#ument to the copy constructor?

Ans : 2f we pass the copy constructor the ar#ument by value, its copy would #et

constructed usin# the copy constructor. This means the copy constructor would callitself to ma5e this copy. This process would #o on and on until the compiler runs out

of memory. This can be e8plained with the help of followin# e8ample:class sample

  &int i '

public :

sample ( sample p +&

i ) p.i '

'

  void main( +

  &sample s '

  sample s ( s + '

/hile e8ecutin# the statement sample s ( s +, the copy constructor would #etcalled. As the copy construct here accepts a value, the value of s would be passed

which would #et collected in p. /e can thin5 of this statement as sample p ) s. erep is #ettin# created and initiali$ed. Oeans a#ain the copy constructor would #et

called. This would result into recursive calls. ence we must use a reference as anar#ument in a copy constructor.

6-.

Qirtual Oultiple 2nheritance:A class b is defined havin# member variable i. Suppose two classes d and d! are

derived from class b and a class multiple is derived from both d and d!. 2f variable i

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 24/55

is accessed from a member function of multiple then it #ives error as member isambi#uous. To avoid this error derive classes d and d! with modifier virtual as

shown in the followin# pro#ram.  %include

class b&

public :int i 'public :

fun( +

&i ) * '

'

class d : virtual public b&

public :fun( +

&

i ) ' '

class d! : virtual public b  &

public :fun( +

&i ) ! '

'

class multiple : public d, public d!

&public :

fun( +&

i ) * '

'

void main( +&

multiple d 'd.fun( + '

cout << d.i '

6@.

Can we use this pointer in a class specific, operatoroverloadin# function for newoperator?

Ans: NoD The this pointer is never passed to the overloaded operator new(+ member

function because this function #ets called before the object is created. ence there is

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 25/55

no 4uestion of the this pointer #ettin# passed to operator new( +.

6.

Can we allocate memory dynamically for a reference?

Ans: NoD 2t is not possible to allocate memory dynamically for a reference. This isbecause, when we create a reference, it #ets tied with some variable of its type.Now, if we try to allocate memory dynamically for a reference, it is not possible to

mention that to which variable the reference would #et tied.

6F.

/hen should 2 overload new operator on a #lobal basis or a class basis?

Ans: /e overload operator new in our pro#ram, when we want to initiali$e a dataitem or a class object at the same place where it has been allocated memory. The

followin# e8ample shows how to overload new operator on #lobal basis.

  %include

%include

void = operator new ( si$e7t s +

&void =4 ) malloc ( s + '

  return 4 '

  void main( +

  &int =p ) new int '

=p ) ! '

  cout << =p '

/hen the operator new is overloaded on #lobal basis it becomes impossible toinitiali$e the data members of a class as different classes may have different types of

data members. The followin# e8ample shows how tooverload new operator on classbyclass basis.

%include

%include

class sample&

int i '

  public :void= operator new ( si$e7t s, int ii +

  &sample =4 ) ( sample = + malloc ( s + '

  4 P i ) ii '  return 4 '

'

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 26/55

  class sample&

float f 'public :

void= operator new ( si$e7t s, float ff +  &

sample =4 ) ( sample = + malloc ( s + '  4 P f ) ff '  return 4 '

'

  void main( +  &

sample =s ) new ( @ + sample '  sample =s ) new ( .-f + sample '

Bverloadin# the operator new on classbyclass basis ma5es it possible to allocate

memory for an object and initiali$e its data members at the same place.

*.

ow would you define a pointer to a data member of the type pointer to pointer?

  Ans: The followin# pro#ram demonstrates this...%include

class sample

  &public :

sample ( int ==pp +

  &p ) pp '

int ==p '

'  int ==sample::=ptr ) ;sample::p '

  void main( +  &

int i ) F '  int =pi ) ;i '

  sample s ( ;pi + '  cout << == ( s.=ptr + '

ere, ptr is the pointer to data member p of class sample, which in turn is a pointer

pointin# to an int.

.

ow do 2 write a code to catch multiple types of e8ceptions in one sin#le catch bloc5?

Ans: The followin# pro#ram demonstrates the use of a sin#le catch bloc5 to catch

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 27/55

multiple e8ceptions.

  %include

class test  &

  '

  class sample

  &

public :void fun( +

  &throw FF '

  void fun!( +

  &throw 0.6f '

  void fun0( +  &

throw >error> '

  void fun6( +

  &throw test( + '

'

  void main( +

  &

try  &

sample s '  s.fun6( + '

  s.fun( + '  s.fun!( + '

  s.fun0( + '

  catch ( ... +

  &cout << >stran#e> '

ere, different types of e8ceptions are thrown by the member functions of the classsample. /hile catchin# the e8ception instead of four different catch bloc5s we can as

well define one sin#le catch bloc5. Note the synta8 for definin# the catch bloc5,where we have used three dots (V+ in the formal parameter list. This indicates that

any thrown e8ception should #et cau#ht in the same catch bloc5. /hen thee8ception is thrown from the fun6( + control reaches the catch bloc5, i#norin# the

rest of the calls.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 28/55

!.Can we return an error value from the constructor of a class?

Ans: No. /e cannot return any error value from the constructor, as the constructor

doesnt have any return type. owever, by throwin# an e8ception we can pass valueto catch bloc5. This is shown in the followin# e8ample:

%include

class sample

  &

public :sample ( int i +

  &if ( i )) * +

throw >error> '

'

void main( +

  &try

  &

sample s ( * + '

  catch ( char = str +&

cout << str '

2n this pro#ram, the statement throw >error> ' would throw an e8ception when an

object s of the class sample would #et created. The catch bloc5 would collect the

strin# error.

0.

ow do 2 define the member function of a template class, which has to be defined

outside the template class. The function receives an object of its own class as a

parameter and returns the value of the same type.

Ans: The followin# e8ample shows how we can define such a function.sample sample::fun ( sample s +

  & 11 code

ere, the first sample indicates the return type of the function and the ne8t sampleis used for the scope of function.

6.ow name man#lin# can be prevented?

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 29/55

Ans: To avoid name man#lin# the function should be declared with an e8tern >C>attribute. 3unctions declared as e8tern >C> are treated as Cstyle functions. ence

the compiler does not man#le them. The followin# code snippet shows how todeclare such a function.

%include

e8tern >C> void display( +  &

cout << >See the effect of C in CEE > '

  void main( +

  &display( + '

.

Can we allocate memory dynamically for a reference?

Ans: No, it is not possible to allocate memory dynamically for a reference. Areference is initiali$ed at the time of creation. Tryin# to allocate memory dynamically

for a reference creates a problem in initiali$in# it. Thus, the compiler does not allowus to dynamically allocate the memory for references.

-./hat is WTT2?

 Ans: WTT2 stands for Wun Time Type 2nformation. /e use virtual function

mechanism where we can call derived classs member functions usin# base classs

pointer. owever, many times we wish to 5now the e8act type of the object. /e can5now the type of the object usin# WTT2. A function that returns the type of the object

is 5nown as WTT2 functions. CEE supports two ways to obtain information about theobjects class at run time, they are typeid( + operator and dynamic7cast operator.

@.

/hat is Iata Conversion?Ans: Assi#nments between types whether they are basic or userdefined, are

handled by the compiler. 2f the variables are of different basic types compiler calls aspecial routine to convert the value. Gut if we want to convert between userdefined

data type and basic types we have to write conversion routine ourselves. Aconversion routine to convert userdefined data type strin# to inte#er is shown

below:  class strin#

  &  private :

  char strJ!*K '  public :

  strin#( +  &

 

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 30/55

  strin# ( char =s +  &

  strcpy ( str, s + ' 

  operator int( +  &

  return !0 ' 11 /rite lo#ic to convert strin# to inte#er    '

  main( +

  &  strin# s! ) >!0> '

  int i ) int ( s! + '  cout << endl << i '

 

.

ow to obtain type information usin# typeid( + operator? 

Ans: typeid( + operator ta5es an object, a reference or a pointer and returns its type.3ollowin# pro#ram shows how to use the typeid( + operator.

 %include

%include

class Gase

  &  public :

  virtual void show( +  &

    '

 

class Ier : public Gase  &

  ' 

void main( +  &

  Gase =b '  cout << endl << typeid ( b +.name( + '

 Ier d '

  b ) ;d '  cout << endl << typeid ( =b +.name( + '

 cout << endl << typeid ( ! +.name( + << endl << typeid ( !. +.name( + '

 

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 31/55

 The output of this pro#ram will be

 Gase=

  Ier  int

  double WTT2 operators must be used for polymorphic class (class havin# virtual function+

only. 3or nonpolymorphic class static type information is returned.

F.ow to use WTT2 with class templates?

 Ans: Templates can #enerate different classes. /e may wish to #et the type of class,

which we are wor5in# in. The followin# pro#ram shows how to use WTT2 operatortypeid( + with class template.

 

%include%include

templateclass base

  &  public :

  base( +  &

  cout << typeid ( =this +.name( + << >Constructor> << endl ' 

 

T add ( T a, T b +  &

  return a E b ' 

 Rbase( +

  &

  cout << typeid ( =this +.name( + << >Iestructor> << endl ' 

  ' 

void main( +  &

  base b '  cout << b.add ( *, !* + << endl '

 base b! '

  cout << b!.add ( ., *. + << endl ' 

-*.

/e can use followin# CEE operators for typecastin#.static7cast is used for castless

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 32/55

conversions, narrowin# conversions, conversion from void= and implicit typeconversions. const7cast is used to convert a const to a nonconst. reinterpret7cast is

used to assi#n one 5ind of pointer to another.

-.

/hat will be the output of the followin# pro#ram? 

%include

class A

  &  public :

  A( +  &

  cout << >Weached in Constructorn> ' 

  ' 

void main( +

  &  A a( + '  A b '

    Butput : Weached in Constructor

 Constructor #ets called only once when the object b is created. /hen the statement

A a( + ' #ets e8ecuted constructor does not #et called. This is because compiler ta5esthis statement as a prototype declaration of function a( + that returns an object of

class A. owever, if we pass ar#uments li5e  A a ( * + '

Compiler would search for one ar#ument constructor and if not found would flash an

error.

-!.

/hat is a container?

Ans: A container is an object that holds other objects. Qarious collection classes li5eHist, ash Table, AbstractArray, etc. are the e8amples of containers. /e can use the

classes to hold objects of any derived classes. The containers provide variousmethods usin# which we can #et the number of objects stored in the container and

iterate throu#h the objects stored in it.

-0.

3unction template overloadin# 

Bne can declare several function templates with the same name and even declare acombination of function templates and ordinary functions with the same name. /hen

an overloaded function is called, overload resolution is necessary to find the ri#ht

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 33/55

function or template function to invo5e.3or e8ample:

  template < class T P T s4rt ( T + '  template < class T P comple8 < T P s4rt ( comple8 < T P + 'double s4rt (

double + '  void f ( comple8 < double P $ +

  &  s4rt ( ! + ' 11 s4rt < int P ( int +  s4rt ( !.* + ' 11 s4rt ( double +

  s4rt ( $ + ' 11 s4rt < comple8 < double P ( comple8 < double P +

  2n the same way that a template function is a #enerali$ation of the notion of a

function, the rules for resolution in the presence of function templates are#enerali$ations of the function overload resolution rules. Gasically, for each template

we find the speciali$ation that is best for the set of function ar#uments. Then weapply the usual function overload resolution rules to these speciali$ations and all

ordinary functions.

-6.

M8ception andlin# in CEE 2n CEE we can handle runtime errors #enerated by cEE classes by usin# three new

5eywords: throw, catch, and try. /e also have to create an e8ception class. 2f durin#the course of e8ecution of a member function of

this class a runtime error occurs, then this member function informs the applicationthat an error has occurred. This process of informin# is called throwin# an

e8ception. The followin# code shows how to deal with e8ception handlin#.  class sample

  &  public :

 

class errorclass  &

  '  void fun( +

  &  if ( some error occurs +

  throw errorclass( + 11 throws e8ception

    '

  11application  void main( +

  &  try

  &  sample s '

  s.fun( + ' 

  catch ( sample::errorclass +  &

  11 do somethin# about the error 

 

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 34/55

-.Consider the followin# code:

 %include

class base  &  public :

  int data '

  ' 

class d : public base  &

  ' 

class d! : public base  &

  '

 class der : public d, public d!

  &

  public :  void showdata( +

  &  cout << data '

  '

 void main( +

  &

  der d '  d.showdata( + '

   

2f you run this pro#ram it is bound to #ive you errors. This is because of the rules ofinheritance:

 

. Mach base class not specified virtual will have its own subobject representin# it.2n the above pro#ram, if we create object of d it will have a subobject of class base

containin# a data member data. 2f we create an object of class der it will have subobjects of classes d and d! and both the subobjects will refer to a separate copy of

data. ence, to access data from class der we will have to mention the class name.3or e8ample, d::data or d!::data.

 !. 2f we want that only one subobject should e8ist we must use the concept of

virtual base class. The sin#le object of this will represent every base class of #ivenname that is specified to be virtual

class. After ma5in# d and d! as virtual base class if we create an object of der onlyone subobject would e8ist and so accessin# data would no lon#er #ive us errors.

--.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 35/55

ow to declare a pointer to a member function? 

Ans: Suppose, 2 wish to declare a pointer to a member function that receives an intand returns an int. 2 will have to declare it as int (A::= + ( int +. 3ollowin# is an

e8ample. 

%include

class A

  &

  public : 

int fun ( int f +  &

  cout << >in funn> ' 

return f = f ' 

  '

 typedef int ( A:: =pfun + ( int + '

 

void main( +  &

  pfun p ) A::fun '  A a '

  int s ) ( a.=p + ( - + '  cout << s '

 

-@.

/hat is the disadvanta#e of a template function? 

Ans: A template function cannot be distributed in the obj form. This is because, withwhich parameters the template function is #oin# to be called is decided at the run

time only. Therefore an obj form of a template function cannot be made by merelycompilin# it.

-.

ow to declare a pointer to the data members of a class?

 Ans: 3ollowin# pro#ram shows how to declare a pointer to nonfunction members of

a class.

%include

class A  &

  public : 

int a '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 36/55

  void print( +  &

  cout << a ' 

  ' 

void main( +  &  int A::=pa ) ;A::a '

 

A obj '  obj.=pa ) !* '

  obj.print( + ' 

 ere, we have initialised the data member a usin# the pointer pa.

-F.ow to allocate memory for a multidimensional array dynamically?

 Ans: Oany times we need to allocate memory for a multidimensional array

dynamically. Gecause of comple8ity of pointers many find this difficult. 3ollowin#pro#ram allocates memory for a 0 8 0 array dynamically, copies contents of a 0 8 0

array in it and prints the contents usin# the pointer. 

%include%include

int aJ KJ0K ) &  , !, 0,

  6, , -,  @, , F

  ' 

void main( +

  &  int ==p '

  p ) new int =J0K '  for ( int i ) * ' i < 0 ' iEE +

  pJiK ) new intJ0K ' 

for ( i ) * ' i < 0 ' iEE +  for ( int j ) * ' j < 0 ' jEE +

  pJiKJjK ) aJiKJjK ' 

for ( i ) * ' i < 0 ' iEE +  &

  for ( j ) * ' j < 0 ' jEE +  cout << pJiKJjK '

  cout << >n> '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 37/55

   

@*.

/hen should we use the :: ( scope resolution + operator to invo5e the virtualfunctions?

 Ans: enerally, :: operator is used to call a virtual function from constructor ordestructor. This is because, if we call a virtual function from base class constructor or

destructor the virtual function of the base class would #et called even if the object

bein# constructed or destroyed would be the object of the derived class. Thus,whenever we want to bypass the dynamic bindin# mechanism we must use the ::

operator to call a virtual function.

@.

ow do 2 use operators .= and P= in a pro#ram?

Ans: The followin# code snippet demonstrates the use of .= and P= operators.

  %include

class sample&

  public :  int i '

  void fun( +&

cout << >fun> << endl ' 

  '

  void ( sample::=pf +( + ) ;sample::fun '

  int sample::=pdm ) ;sample::i '

  void main( +&

  sample s '

  sample =p ) new sample '

  ( s .= pf +( + '

  ( p P= pf +( + '

s .= pdm ) '

  p P= pdm ) ! '

  cout << s .= pdm << endl '  cout << p P= pdm << endl '

  2n the above pro#ram pf is a pointer to a function fun( + of class sample, and pdm is

a pointer to a data member i of the same class sample. The object s of the class

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 38/55

sample is created statically. Ne8t, p is a pointer to an object created dynamically.The usin# the operator .= and P= the member functions are called and also the

public data member is accessed.

@!.

/hat happens when we add an int value to a user defined type of object?

Ans: /henever an int value is added to an object of user defined type, the object

would search for an overloaded operator int( +. This operator must be defined in

such a way that it always returns an int value. owever, we need not specify thereturn type as on doin# so the compiler flashes an error.

  %include

class sample  &

  int i '

  public :

  sample ( +  &  i ) * '

    operator int( +

  &  return this P i '

    '

  void main( +  &

  sample s '

int i '  i ) s E * '

  cout << i ' 

 2n the above pro#ram on addin# * to an object s, the value of i would become !*.

@0.Can we have a reference to an array?

Ans: "es, we can have a reference to an array.

  int aJ K ) & , !, !, F '  int ( ;r + J 6 K ) a ' 11 reference to an array

ere, r is a reference to an array of four elements. /e can even print the elements

of array with the help of reference. This is shown in the followin# code se#ment:

  for ( int i ) * ' i < 6 ' iEE +cout << r JiK << endl '

@6.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 39/55

/hen friend function becomes indispensable... 

Ans: Consider the followin# pro#ram. 

%includeclass distance

  &  private :  int feet '

  public :

  distance( +  &

  feet ) * ' 

  distance ( int f +  &

  feet ) f ' 

  distance operator E ( distance 8 +

  &  int f ) feet E 8.feet '  return distance ( f + '

    '

  void main( +  &

  distance d ( !* +, d!, d0 '  d! ) d E * '

  d0 ) * E d! ' 

 

2f you run this pro#ram it is bound to #ive errors. The error lies in the statement d0) * E d! ' /e may thin5 that since we have overloaded E operator this statement

would add * to d!. Gut this does not happen. This is because the specifiedstatement will #et converted as d0 ) *.operatorE ( d! + ' This means that this

statement should call the operatorE( + function that ta5es an object of distance classas parameter written in

the float class, which is not possible. The solution is to write operatorE( + as a

friend function. Ieclare operatorE function in distance class as #iven below: 

friend distance operator E ( distance 8, distance 8! + ' 

and define it outside the class as shown below: 

distance operator E ( distance 8, distance 8! +  &

  int f ) 8.feet E 8!.feet '  return distance ( f + '

   

/hen compiler would see that the friend operatorE( + function is available it wouldconvert the statement d0 ) * E d! as operatorE (*, d! +. Now since * is passed

as a parameter not as a callin# object there would be no error. Thus in such cases

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 40/55

friend function becomes indispensable.

@.

ow to use a memory as a stream? 

Ans: Suppose, details of an employee such as name, desi#nation, a#e, etc. arestored in different types of variables. Now, if we wish to concatenate these details ina character array we will have to use various strin# manipulation functions li5e

strcpy( + and strcat( +. 2nstead of usin# these functions we can use more easy and

clean way to #ather the details in the char array in the form of streams. /e candeclare the memory allocated for the array as stream and use the << operator to

store variables havin# different types in this memory. 3ollowin# pro#ram shows howto achieve this.

  %include  void main( +

  &  char buff J*K '

  char strJ K ) >Sanjay> '

  char desi#J K ) >Oana#er> '  char jdJ K ) >!@1!1FF> '  int a#e ) 0 '

  ostrstream o ( buff, si$eof ( buff + + '  o << str << endl << desi# << endl << jd << endl << a#e << ends '

  cout << buff ' 

  As shown in the pro#ram we can also use the manipulators and formattin# fla#s.The output of this pro#ram will be:

  Sanjay  Oana#er

  !@1!1FF

  0

@-.ow would you declare and initiali$e reference to a data member?

Ans: Sometimes we may need to declare a data member, which is a reference to

another data member of the class as shown below: 

class A  &

  public :  char =p '

  char =;rp '  '

 /e cant initiali$e a reference to a data member at the time of declaration. 2t should

be initiali$ed usin# member wise initiali$ation as shown below. 

%includeclass A

  &

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 41/55

  public :  char =p '

  char =;rp '  A( + : rp ( p +

  &  p ) >> '

   

A ( char =s + : rp ( p +

  &

  p ) s ' 

  ' 

void main( +  &

  A a ( >abcd> + '  cout << a.rp '

 

 @@.iostream library has made it easy to read data from various input devices and write

data to the output devices. The followin# pro#ram shows how to print a dis5 filedata.dat on the printer usin# stream classes. Mvery hardware device has a familiar

name #iven by the operatin# system. The printer is #enerally connected to the firstparallel port. So, the file name for the printer should be WN or lpt.

  %includevoid main( +

  &  ifstream i ( >data.dat> + '

  ofstream o '

  o.open ( >WN> + '  char ch '

  while ( +  &

  i.#et ( ch + '  if ( i.eof( + +

  brea5 '

  o.put ( ch + ' 

  o.put ( 8*C + ' 

@.

/e 5now that a destructor is automatically called when an object of a class #oes outof scope. There is another case where destructor is called automatically. 2f an object

is created in a try bloc5 and an e8ception is thrown after the object is created, thenthe destructor is called automatically.

@F.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 42/55

Can a function call be at the left hand side of the assi#nment operator? 

Ans: "es. 3ollowin# pro#ram shows how it is possible.%include

class ref&

private :struct data&

int a ' char =p '

d, d! 'public :

data ;set ( +&

return d '

data ;#et ( +&

cin PP d!.a PP d!.p '

return d! ' '

void main( +&

ref r 'r.set( + ) r.#et( + '

r.print( + '

2n the above pro#ram the functions #et( + and set( + both return a reference to theobject of the structure data. /e have assi#ned the reference returned by #et( + to

the reference returned by set( + function. That is, we are assi#nin# d! to d. So, the

values of d! would #et assi#ned to d. "ou can chec5 this out by printin# the valuesof d.

*.

2f a class contains a virtual function a pointer called QTW is created. This QTWbecomes a part of every object of that class. The first two bytes (in IBS+ are

occupied by QTW. /e can prove this by displayin# the first two bytes of memoryallocated for the objects. 3ollowin# pro#ram shows how this can be achieved.

 %include

class vir

  &  public :

  virtual void f( +  &

    '

 

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 43/55

  void main( +  &

  vir v, v '  int =p ) ( int= + ;v '

  int =p! ) ( int= + ;v ' 

cout << endl << =p << > > << =p! ' 

.

M8ception andlin# in CEE 

2n CEE we can handle runtime errors #enerated by cEE classes by usin# three new5eywords: throw, catch, and try. /e also have to create an e8ception class. 2f durin#

the course of e8ecution of a member function ofthis class a runtime error occurs, then this member function informs the application

that an error has occurred. This process of informin# is called throwin# ane8ception. The followin# code shows how to deal with e8ception handlin#.

  class sample

  &  public : 

class errorclass  &

  '  void fun( +

  &  if ( some error occurs +

  throw errorclass( + 11 throws e8ception 

  '

  11application  void main( +

  &  try

  &  sample s '

  s.fun( + '

    catch ( sample::errorclass +

  &  11 do somethin# about the error

   

!.

Accessin# a private data member from a different Bbject... 

Iifferent objects of the same class can access each others members, even if thesemembers are private. 3or e8ample:

  %include < iostream.h P

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 44/55

  class sample  &

  float f '  public :

  sample ( float ff +  &

  f ) ff '    void fun ( sample= objptr +

&

objptr P n ) * '  cout << >Qalue of this objects f is : > << f << endl '

  cout << >Qalue of other objects f> << objptr P n << endl '  11 another objects private memberD

  '  void main( +

  &  sample s ( -.f + , s! ( !.f + '

  s.f ( ;s! + ' 11 s chan#es s!s n

  Typically, this codin# style should be avoided. owever, you should be aware thatprivate members of an object can be chan#ed by another object of the same type.

Therefore, in certain special conditions, this codin# style may be useful.

0.

Can you access private data members of a class from out side the class?  Ans: "es. This pro#ram shows how.

  %includeclass emp

  private :

int i '  public :

  emp( +  &

  i ) * ' 

  '

  void main( +  emp =p ) new emp '

  int =pi ) (int=+ p '  cout << =pi '

  =pi ) !* '  cout << =pi '

   

The pointer to the class is typecasted in an inte#er pointer. /ith the help of thispointer private data member i is accessed in main( +.

6./hy creatin# array of references is not possible?

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 45/55

Ans: The array name always refers or points to the $eroeth element. 2f array is ofreferences then the array name would point to the $eroeth element which happens

to be a reference. Creatin# pointer to a reference is not valid. So, creatin# array ofreferences too is not possible.

.ow do 2 call a virtual function of a class usin# a pointer to a function ?  Ans :

%include

class Cvirtual  &

  public :  virtual float vfun( +

  &  cout << >from vfun> << endl '

  return @.*0f ' 

  '

  void main( +  &  Cvirtual obj '

  int ==p ) ( int == + ;obj '  float ( =pf + ( + '

  pf ) ( float ( = + ( + + ==p '  float f ) ( =pf + ( + '

  cout << >return val ) > << f << endl ' 

 2n the above pro#ram class Cvirtual consists of a virtual function vfun(+. 2n variable p

we have stored the address of an object of class Cvirtual. /hile doin# so, we have

type casted the address of obj to int ==, because obj holds a hidden data membercalled vptr, which in turn holds the address of virtual function vfun( +. 2n pf, a

pointer to a function, we are collectin# the address of the virtual function vfun( +.Thus the value returned by vfun( + would then #et collected in f.

-.

/hy an overloaded new operator defined in a class is static? 

Ans: An overloaded new function is by default static even if it is not declared so.This is because nonstatic member functions can be called throu#h an object only.

Gut when an overloaded new operator function #ets called the object doesnt standcreated. Since new operator function itself is responsible for creatin# the object.

ence to be able to call a function without an object, the function must be static.

@.

/hat is a pure virtual destructor? 

Ans: Hi5e a pure virtual function we can also have a pure virtual destructor. 2f a base

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 46/55

class contains a pure virtual destructor it becomes necessary for the derived classesto implement the destructor. An ordinary pure virtual function does not have a body

but pure virtual destructor must have a body. This is because all the destructors inthe hierarchy of inheritance are always called as a part of destruction.

./hen we are re4uired to find offset of an element within a structure? or, how do wecall the function of an outer class from a function in the inner class? (The inner class

is nested in the outer class+

  Ans:  %include

class outer&

int i 'float f '

public :class inner

&

public :infunc( +&

outer =pout 'pout ) (outer=+ this ( si$e7t + ;( ( ( outer= + * + P in + '

pout P outfunc( + '

'inner in '

outfunc( +&

cout << >in outer classs function> '

'

void main( +&

outer out 'out.in.infunc( +

2n the above e8ample we are callin# outer::outfunc( + from inner::infunc(+. To calloutfunc( + we need a pointer to the outer class. To #et the pointer we have

subtracted offset of the inner classs object (base address of outer classs object address of inner classs object+ from address of inner classs object.

F.

void f ( float n, int i ) * + '

  void f ( float a + '  void main( +

  &  f ( !.- + '

   

void f ( float n, int i +

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 47/55

  & 

 

void f ( float n +  &

 

 

The above pro#ram results in an error (ambi#uous call+ since without the default

ar#ument the two functions have ar#uments that are matchin# in number, order andtype.

F*.Some pro#rams need to e8ercise precise control over the memory areas where data

is placed. 3or e8ample, suppose we wish to read the contents of the boot sector intoa structure. 3or this the byte arran#ement of the

structure elements must match the arran#ement of various fields in the boot sector

of the dis5.

The %pra#ma pac5 directives offer a way to fulfill this re4uirement. The %pra#ma

pac5 directive specifies pac5in# ali#nment for structure and union members. The%pra#ma ta5es effect at the first structure or union declaration after the

%pra#ma is seen. Consider the followin# structure:%pra#ma pac5 (+

struct emp&

int a 'float s '

char ch '

'%pra#ma pac5( +

ere, %pra#ma pac5 ( + lets each structure element to be#in on a byteboundary. ence the si$e of the structure will be F. (int 6, float 6, char +. 2f we

use %pra#ma pac5 ( ! + each structure element can be#in on a !byte boundary.ence the si$e of the structure will be *. (int 6, float 6, char !+.

F.

ow to restrict a friend classs access to the private data members?

Ans: 2f we declare a class as a friend of our class the friend class can access theprivate data members of our class. owever, if we want we can restrict this access to

some selective functions of the class. 3ollowin# pro#ram shows how to achieve this: 

%includeclass X

&public :

void print ( class Y ;$ + ' '

class Y

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 48/55

  &private :

int i 'public :

Y ( int ii +&

i ) ii 'friend X::print ( class Y ;$ + '

'

void X::print ( Y ;$ +&

cout << $.i '

main( +&

Y $ ( * + 'X 8 '

8.print ( * + '

 2n the above pro#ram only the X::print( + function can access the private data

members of class Y.

F!.

/hat is name man#lin#?

 Ans: CEE enables you to assi#n the same function name to more than one functions

but with different parameter types. This feature is called function overloadin#. Gut

when we #ive several functions the same name, how does the compiler decide whichparticular function is to be called? CEE solves this problem by applyin# a process

called name man#lin#. Name man#lin# applies a decorated name to the function.The man#led name includes to5ens that identify the functions return type and the

types of its ar#uments.

class test

  &  public :

  void fun ( int a, char b + '  void fun ( char =c, float y + '

  ' 

void main( +  &

  test s '  s.fun ( -, A + '

  s.fun ( >Anil>, .f + ' 

At the time of resolvin# the calls to fun( + function the lin5er would not be able tofind the definition of the overloaded function fun( + and it would report an error. 2f

you loo5 at these errors you will see the man#led names li5e, (?

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 49/55

funZtestZZ[AMX\\ZY+ and (?funZtestZZ[AMXOOZY+. Note that differentcompilers may use different name man#lin# schemes.

F0.

ow would you call a C function from CEE code?Ans: 9sin# e8tern >C>.

The function prototype must be preceded by e8tern >C>. Oore than one C functionscan be #rouped inside braces as shown below:

e8tern >C>

&

void f( + 'void f( + '

 11 2n cfunc.c

%includevoid f( +

&printf ( >in f( +> + '

 11 2n func.cpp%includee8tern >C> void f( + '

void main( +&

f( + '

Mnsure that both .c and .cpp files are in the same project.

F6.ow to restrict the number of floatin#point di#its displayed ?

Ans: /hen we display floatin#point values, we can use the setprecision manipulator

to specify the desired number of di#its to the ri#ht of the decimal point.  3or e8ample,

 

cout << setprecision ( 0 + << !.06-@ ' 

This statement would #ive the output as !.06@.

F.

/hat is a wild pointer ? 

Ans: A wild pointer is the one that points to a #arba#e value. 3or e8ample, anuninitiali$ed pointer that contains #arba#e value or a pointer that refers to somethin#

that no lon#er e8ists.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 50/55

F-.ow friend function helps to increase the versatility of overloaded operators?

Ans: Consider the followin# statement,

s! ) s = ! 'where, s and s! are objects of sample class. This statement would wor5 if the

overloaded operator = ( sample s + or conversion function is provided in the class.2nternally this statement would #et converted to,

s! ) s.operator = ( ! + '

The function materiali$es because it is called with an object s. The this pointer of swould #et passed implicitly. To collect ! in s, first the compiler would call the one

ar#ument constructor, then it would build anameless object, which then would #et collected in s. owever, if we write the

above statement as,s! ) ! = s '

then it wont compile. This is because the call now would #et treated as,s! ) !.operator = ( s + '

and ! is not an object. The friend function helps to #et rid of such a situation. This is

shown in the followin# pro#ram.%include

class sample  &

private :int i '

public :sample ( int ii ) * +

  &i ) ii '

  void showdata( +

  &cout << i << endl '

  friend sample operator = ( sample, sample + '

'

  sample operator = ( sample s, sample s! +  &

sample temp '  temp.i ) s.i = s!.i '

  return ( temp + '

  void main( +

  &sample s ( * +, s! '

s! ) s = ! '

  s!.showdata( + '

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 51/55

  s ) ! = s! '

  s.showdata( + '

ere the operator =( + function ta5es two parameters. This is because the operator

function is no lon#er a member function of the class. 2t is a friend of the classsample. Thus the statement s! ) s = ! ' would not ta5e the form s!.operator =( ! +. This e8ample shows that usin# friend permits the overloaded operators to be

more versatile.

F@.

/hat is a const7cast?

Ans: The const7cast is used to convert a const to a nonconst. This is shown in the

followin# pro#ram.%include

void main( +  &

const int a ) * '

  int =ptr ) ( int = + ;a ' 11 one way

  ptr ) const7cast ( ;a + ' 11 better way

ere, the address of the const variable a is assi#ned to the pointer to a nonconst

variable. The const7cast is also used when we want to chan#e the data members ofa class inside the const member functions. The followin# code snippet shows how to

do this.

class sample&

private :int data '

public :void fun( + const

  &

( const7cast ( this + + P data ) @* '

'

F.

9sin# a smart pointer we can ma5e an object appear li5e a pointer.

2f a class overloads the operator P then any object of that class can appear li5e apointer when the operator P ( + is called. The followin# pro#ram illustrates this.

%include

class test  &

public :

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 52/55

  void fun( +&

cout << >fun of smart pointer> '

'

  class smartpointer  &

test t '

public :

test= operator P( +  &

return ;t '

'

  void main( +  &

smartpointer sp '

  sp P fun( + '

The beauty of overloadin# operator P is that even thou#h sp is an object we can

ma5e it wor5 li5e a pointer. The operator P ( + returns the address of the object ofthe type test. 9sin# this address of the test object the function fun( + of the class

test #ets called. Thus even thou#h fun( + is not a member of smartpointer class wecan still call it usin# sp.

FF.

Can we apply delete on this pointer inside a member function?

Ans : "esD 2f the member function of a class is called usin# a pointer to an object,

which is allocated dynamically, the object would #et deleted. Gut if the memberfunction is called usin# the object, which is allocated statically, then a runtime error

would occur. This is because we cannot call delete on statically allocated objects.This is illustrated in the followin# e8ample.

class sample

&private :

int i 'public :

void fun( +  &

delete this '

'

void main( +  &

sample =s ) new sample '  s P fun( + ' 11 no error

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 53/55

  sample s '  s.fun( + ' 11 would throw a runtime error

**./hy cant data members of a class be initiali$ed at the time of declaration as #iven

in the followin# code?  class emp  &

  private :

  int j ) * '  '

Ans: Oemory for data members of a class is allocated only when object of that classis created. Bne cannot store data in a memory location, which does not e8ist at all.

Therefore initiali$ation at the time of declarationis not possible.

*.

/hy in a copy constructor an object is collected in a reference to object as shownbelow?

%includeclass emp

  &  public :

  emp( +  &

    emp ( emp; +

  &

  cout << >copy> ' 

  '  void main( +

  &  emp e '

  emp e ) e '

  Ans: A copy constructor is called when an object is created and initialised at the

same time. 2t is also called when object is passed to a function. So, 2f we pass theobject to copy constructor copy constructor would #et called recursively. Thus it will

stuc5 up in an infinite loop.

*!.

/hat is Marly Gindin# and Iynamic Gindin#?

Ans: The term bindin# refers to the connection between a function call and the actualcode e8ecuted as a result of the call. Marly Gindin#: 2f which function is to be called is

5nown at the compiletime it is 5nown as static or early bindin#. Iynamic Gindin#: 2fwhich function is to be called is decided at run time it is called as late or dynamic

bindin#. Iynamic bindin# is so called because the actual function called at runtime

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 54/55

depends on the contents of the pointer. 3or e8ample, call to virtual functions, call tofunctions to be lin5ed from dlls use late bindin#.

*0./hen can we use the function ostrstream::free$e( +?

Ans: /hile outputtin# data to memory in the inmemory formattin# we need tocreate an object of the class ostrstream. The constructor of ostrstream receives the

address of the buffer but if we want that the ostrstream

object should do its own memory mana#ement then we need to create an ostrstreamobject with no constructor ar#uments as:

ostrstream s 'Now s will do its own memory mana#ement. /e can stuff as many bytes into it as

we want. 2f it falls short of memory, it will allocate more memory. 2f it cannot, it mayeven move the bloc5 of memory. /hen the object #oes out of scope, the heap

stora#e is automatically released. This is a more fle8ible approach if we do not 5nowhow much space we are #oin# to need. 2f we want the physical address of the

memory used by s we can obtain it by callin# the str( + member function:

char= p ) s.str( + 'Bnce str( + has been called then the bloc5 of memory allocated by ostrstream cannotbe moved. This is lo#ical. 2t cant move the bloc5 since we are now e8pectin# it to be

at a particular location. 2n such a case wesay that ostrstream has free$ed itself. Bnce fro$en we cant add any more characters

to it. Addin# characters to a fro$en ostrstream results in undefined behavior. 2naddition, the ostrstream is no lon#er responsible for cleanin# up the stora#e. "ou

too5 over that responsibility when you as5ed for the char = with str( +. /e can cleanthe stora#e in two ways: 9sin# the delete operator as shown below:

ostrstream s '  char =p '

  p ) s.str( + '

  delete p 'Gy unfree$in# the ostrstream. "ou do this by callin# free$e( +, with an ar#ument .

Iurin# free$in# it is called with the default ar#ument of *.

8/13/2019 C Notes for beginners

http://slidepdf.com/reader/full/c-notes-for-beginners 55/55