POP Notes
POP Notes
What do you mean by a reference variable? Is there any hiding or information hiding.
difference between reference variable and pointer? Explain The wrapping up of data and functions into a single unit
with example. (called class) is known as encapsulation. Data encapsulation
Answer: C++ references allows to create a second name for is the most striking feature of a class. The data is not
the a variable that one can use to read or modify the original accessible to the outside world, and only those functions,
data stored in that variable, what this means is that, when which are wrapped in the class, can access it. These functions
some one declare a reference and assign it a variable, it will provide the interface between the object's data and the
allow to treat the reference exactly as though it were the program. This insulation of the data from direct access by the
original variable for the purpose of accessing and modifying program is called data hiding.
the value of the original variable--even if the second name
(the reference) is located within a different scope. When do you declare a member of a class static?
Example: int x; Answer: A data member of a class can be qualified as static. A
int &y=x; // Here, y is the alias or second name of x. A pointer member function of a class is declared static when,
has its own memory address and size on the stack (4 bytes on Only one copy of that member is required for the entire class
x86), whereas a reference shares the same memory address and is shared by all the objects of that class, no matter how
but also takes up some space on the stack Since a reference many objects are created. It's visible should be within the
has the same address as the original variable itself, it is safe class, but its lifetime is the entire program. Static variables
to think of a reference as another name for the same are normally used to maintain values common to the entire
variable. class.A static function can have access to only other static
members (members or variables) declared in the same class.
What is friend function? What is const. member function?
Answer: As per the concept, when a data is declared as Answer: Member functions should be declared with the
private inside a class, then it is not accessible from outside const keyword after them if they can operate on a const (this)
the class. A function that is not a member or an external class object. If the function is not declared const, in can not be
will not be able to access the private data. A programmer applied to a const object, and the compiler will give an error
may have a situation where he or she would need to access message. A const function can be applied to a non-const
private data from non-member functions and external object.A function can only be declared const if it doesn't
classes. For handling such cases, the concept of Friend modify any of its fields.
functions is a useful tool. A friend function is used for
accessing the non-public members of a class. A class can Why should the formal argument of a copy constructor be a
allow non-member functions and other classes to access its reference object?
own private data, by making them friends. Thus, a friend Ans: When a function takes an object as argument, instead
function is an ordinary function or a member of another of, e.g., a pointer or a reference, the copy constructor is
class. A friend function of a class is defined outside that class' called to pass a copy of an object as the argument. This
scope but it has the right to access all private and protected argument, which usually is passed via the stack, is therefore a
members of the class. Even though the prototypes for friend new object. It is created and initialized with the data of the
functions appear in the class definition, friends are not passed argument. A reference parameter avoids extra stack
member functions. A friend can be a function, function usage and a call to the copy constructor.
template, or member function, or a class or class template, in
which case the entire class and all of its members are friends. What are destructors? When are they called? What is their
To declare a function as a friend of a class, precede the utility?
function prototype in the class. Answer: Comparable to the constructor, classes may define a
destructor. This function is the opposite of the constructor in
What is the significance of "this" pointer? the sense that it is invoked when an object ceases to exist.
Answer: The this keyword is a pointer variable, which always the blockin which the object is defined is left: the destructors
contains the address of the object in question. The this of objects that are defined in neste blocks of functions are
pointer is implicitly declared in each member function therefore usually called before the function itself terminates.
(whether public. protected, or private). Therefore, it is as if The destructors of objects that are defined somewhere in the
each member function of the class Person contains the outer block of a function are called just before the function
following declaration: extern Person const this: returns (terminates). For static or global variables the
destructor is called before the program terminates. It is
Mention the salient feature of constructor. mainly used for freeing the memory space used by the
Ans: Classes have a special member function called a previous processes. However, when a program is interrupted
constructor. The constructor can take using an exit() call, the destructors are called only for global
objects existing at that time. Destructors of objects defined
parameters as needed, but it cannot have a return value-not locally within functions are not called when a program is
even void. The constructor is a class method with the same forcefully terminated using exit().
name as the class itself. Whenever you declare a constructor,
you'll also want to declare a destructor. Just as constructors What is default constructor?
create and initialize objects of your class, destructors clean Answer: Default constructors usually not being defined
up after your object and free any memory you might have explicitly in a program, it is of course possible to define a
allocated. A destructor always has the name of the class, class with no constructor at all. In that case the program will
preceded by a tilde (-). Destructors take no arguments and call a default constructor when a corresponding object is
have no return value. If you don't declare a constructor or a created. What actually happens in that case depends on the
destructor, the compiler makes one for you. The default way the class has been defined.
constructor and destructor take no arguments and do
nothing. When you define an object of a class, the
constructor is called. In simple words, Constructor functions
are Member Functions of a class having some special
property.
Friend Function: As per the concept, when a data is declared State the basic differences between a 'Structure' in C and a
as private inside a class, then it is not accessible from outside 'Class' in C++,
the class. A function that is not a member or an external class Answer: C++ supports all the features of structures as
will not be able to access the private data. A programmer defined in C. But C++ has expanded its capabilities further to
may have a situation where he or she would need to access suit its OOP philosophy. It attempts to bring the user-defined
private data from non-member functions and external types as close as possible to the built-in data types, and also
classes. For handling such cases, the concept of Friend provides a facility to hide the data which is one of the main
functions is a useful tool. A friend function is used for precepts of OOP. Inheritance, a mechanism by which one
accessing the non-public members of a class. A class can type can inherit characteristics from other types, is also
allow non-member functions and other classes to access its supported by C++. In C++, a structure can have both variables
own private data, by making them friends. Thus, a friend and functions as members. It can also declare some of its
function is an ordinary function or a member of another members as 'private' so that they cannot be accessed directly
class. by the external functions.In C++, the structure names are
stand-alone and can be used like any other type names. That
What is virtual destructor? is, the keyword struct can be omitted in the declaration of
Answer: A virtual call is a mechanism to get work done on structure variables. For example, we can declare the student
given partial information. In particular, "virtual" allows us to variable A as student A; // C++ declaration This is an error in
call a function knowing only any interfaces and not the exact C. C++ incorporates all these extensions in another user-
type of the object. To create an object you need complete defined type known as class. There is very little syntactical
information. In particular, you need to know the exact type of difference between structures and classes in C++ and,
what you want to create. Consequently, a "call to a therefore, they can be used interchangeably with minor
constructor" cannot be virtual. A constructor cannot be modifications. Since class is a specially introduced data type
virtual because at the time when the constructor is invoked in C++, most of the C++ programmers tend to use the
the virtual table (virtual table) would not be available in the structures for holding only data, and classes to hold both the
memory. Hence we cannot have a virtual constructor. Again data and functions.
in case of inheritance, base class constructor is available in
derived class, when we create derived class object base class Data encapsulation:Encapsulation is the process of
constructor gets called first. After that derived class combining data and functions into a single unit called class.
constructor gets called Using the method of encapsulation, the programmer cannot
directly access the data. Data is only accessible through the
What is containership? How does it differ from inheritance? functions present inside the class. Data encapsulation led to
Answer:1st Part: Manipulators are operators used in C++ for the important concept of data hiding. Data hiding is the
formatting output. The data is manipulated by the implementation details of a class that are hidden from the
programmer's choice of display. There are numerous user. The concept of restricted access led programmers to
manipulators available in C++. Some of the more commonly write specialized functions or methods for performing the
usedmanipulators are: endl, setw, setfill, etc.When a class operations on hidden members of the class. Attention must
contains objects of another class or its members, this kind of be paid to ensure that the class is designed properly.
relationship is called containership or nesting and the class Encapsulation leads to the concept of data hiding, but the
which contains objects of another class as its members is concept of encapsulation must 'not be restricted to
called as container class. Containership is basically type of information hiding. Encapsulation clearly represents the
hierarchy. It can also be called containment hierarchy. In ability to bundle related data and functionality within a
other words, possessing of objects of other classes in a class single, autonomous entity called a class.
is called containership or nesting.
2nd Part: Although Inheritance and Containership are two Why is it necessary to overload an operator?
OOP concepts, they are quite different in what they allow the Answer: One of the C++ language's many intriguing features
programmer to achieve. Inheritance is the ability for a class is operator overloading. It is a crucial method that has
to inherit properties and behavior from a parent class by improved C++'s extension capabilities. The attempt to have
extending it. user-defined data types behave similarly to built-in types is
one of C++'s key features. For instance, using the same syntax
as for fundamental types, C++ enables us to add two
variables of user-defined kinds. In other words, C++ can
provide an operator a unique meaning specific to a data type.
Overloading the increment operator (operator()) and Distinguish multiple inheritance from multilevel inheritance
decrement operator creates a little problem: there are two with suitable examples.
version of each operator, as they may be used as postfix Answer: Their name always tion of the relation,
operator (eg, x++) or as prefix operator (e.g. ***). onships between two eir relationship as ancle, say acircle, is a
Ams: Used as postfix operator, the values object is returned you can move pointsin this direction by
as value, which is an expression having a fixed value: the Multiple inheritances allow us to combine the features of
post-incremented variable itself disappears from view. Used several existing classes as a starting point for defining new
as prefix operator, the variable is incremented, and its value classes. Now, in case of multilevel inheritance, a class is
is returned as Ivalue, so it can be altered immediately again. derived from another derived class. Suppose a class is
Whereas these characteristics are not required when the derived from one class, which in turn serves as a base class
operator is overloaded, it is strongly advised to implement for another derived class. So, here the features inheriting
these characteristics in any overloaded increment or continue level by level. Suppose the class A serves as a base
decrement operator. class for the derived class B which in turn serves as a base
Overloaded increment operators without parameters are class for the derived class C. The class B is known as
prefix operators, and should return references to the current intermediate base class since it provides a link for the
object. Overloaded increment operators having an int inheritance between A and C. The chain ABC is known as
parameter are postfix operators, and should return the value inheritance path.
the object has at the point the overloaded operator is called
as a constant value. When the object has a more complex What is inheritance? Mention some advantages of
data organization using a copy constructor might be inheritance?
preferred. For instance, assume we want to implement the
postfix increment operator in the class PersonData. b) Describe different types of inheritance with examples.
Presumably, the PersonData class contains a complex inner Answer:
data organization. If the PersonData class would maintain a a) Inheritance is a mechanism of reusing and extending
pointer Person current to the Person object that is existing classes without modifying them, thus producing
currently selected . hierarchical relationships between them. Inheritance is
What is 'has-a' relationship? How is this implemented? almost like embedding an object into a class. Suppose that
In database design and object oriented program architecture, you declare an object x of class A in the class definition of B.
has-a is a relationship where one object (often called the As a result, class B will have access to all the public data
composited object) "belongs" to (is a part or member of) members and member functions of class A. However, in class
another object (called the composite type), and behaves B, you have to access the data members and member
according to the rules of ownership. In simple words, has-a functions of class A through object x. Inheritance offers the
relationship in an object is called a member field of an following advantages--
object. Multiple has-a relationships will combine to form a 1. Development model closer to real life object model with
possessive hierarchy. In object-oriented programming this hierarchical relationships 2. Reusability-facility to use public
relationship can be represented with a Unified Modeling methods of base class without rewriting the same 3.
Language diagram. This has-a relationship is also known as Extensibility-extending the base class logic as per business
composition. As you can see from the diagram on the right a logic of the derived class 4. Data hiding-base class can decide
car "has-a " carburetor, or a car is "composed of a carburetor. to keep some data private so that it cannot be altered by the
When the diamond is coloured black it signifies composition, derived class.
i.e. the object on the side closest to the diamond is made up b) The derived class inherits some or all of the traits or
of or contains the other object. While the white diamond properties from the base class. A class can also inherit
signifies aggregation, which means that the object closest to properties from more than one class or from more than one
the diamond can have or possess the other object. level. A derived class with only one base class is called single
inheritance and one with several base classes is called
multiple inheritances. Multiple inheritances allow us to
combine the features of several existing classes as a starting
point for defining new classes. Now, in case of multilevel
inheritance, a class is derived from another derived class.
Suppose a class is derived from one class, which in turn
serves as a base class for another derived class. So, here the
features inheriting continue level by level. On the other hand,
What are the ambiguities that arise in multiple inheritance? for further inheritance. A protected member, inherited in the
How can they be resolved? private mode derivation, becomes private in the derived
Answer: In object-oriented programming languages with class. Although it is available to the member functions of the
multiple inheritance and knowledge organization, the derived class, it is not available for further inheritance (since
diamond problem is an ambiguity that arises when two private members cannot be inherited). The following table
classes Ban inherit from A, and class D inherits from both B summarizes how the visibility of members undergoes
and C. If a method in D calls a method defined in A (and does modifications when they are inherited. The keywords private,
not override the method), and B and C have overridden that
method differently, then from which class does it inherit: B, Write short notes on: Constructor call in inheritance
or C? Let us consider a situation of hybrid inheritance, where Answer: A derived class inherits the functionality from its
multiple, multilevel and hierarchical inheritance is involved, base class. In this section we shall describe the effects
as shown in the fig.The child has two direct base classes inheritance has on the constructor of a derived class. As will
parent and parent2 which themselves have a common base be clear from the definition of the class Land, a constructor
class grandparent. The child inherits the properties of exists to set both the weight and the speed of an object. The
grandparent via two separate paths. It can also inherit poor-man's implementation of this constructor could be:
directly as shown by broken lines. The grandparent is Land::Land (size_t weight, size_t speed) t
sometimes referred to indirect base class. Now this type of setWeight (weight): setspeed (speed);
inheritance may create some problem for the child class, This implementation has the following disadvantage. The C++
because all the public and protected members of compiler will generate code calling the base class's default
grandparent are inherited twice into it. This means, child constructor from each constructor in the derived class,
would have duplicate sets of members inherited from unless explicitly instructed otherwise Consequently, in the
grandparent. This problem can be avoided by declaring the above implementation the default constructor of Vehicle is
common base class as virtual base class. For the above called, which probably initializes the weight of the vehicle,
problem the virtual base class can be declared in the only to be redefined immediately thereafter by the function
following way: class Grandparent. setweight(). A more efficient approach is of course to call the
constructor of Vehicle expecting a size_t weight argument
What do you mean by access modifiers of visibility levels directly. The syntax achieving this is to mention the
What is runtime polymorphism? constructor to be called (supplied with its arguments)
immediately following the argument list of the constructor of
C++ supports another important feature, known as run time the derived class itself. Such a base class initializer is shown
polymorphism. This can be achieved with the help of virtual in the next example. Following the constructor's head a colon
functions. At run time, when it is known what class objects appears, which does the base class.
are under consideration, the appropriate version of function
is invoked. Since the function is linked with a particular What is runtime polymorphism?
class much later after the compilation, this process is C++ supports another important feature, known as run time
known as late bindinginheritance? What are the different polymorphism. This can be achieved with the help of virtual
access modifiers in case of inheritance in C++? functions. At run time, when it is known what class objects
Answer: There may be some situations where private data are under consideration, the appropriate version of function
needs to be inherited by a derived class. This can be is invoked. Since the function is linked with a particular class
accomplished by modifying the visibility limit of the private much later after the compilation, this process is
member by making it public. This would make it accessible to known as late binding.
all the other functions of the program. thus eliminate the
advantage of data hiding. C++ provides a third visibility
modifier, protected, which serve a limited purpose in
inheritance. A member declared as protected is accessible by
the member functions within its class and any class
immediately derived from it. It cannot be accessed by the
functions outside these two classes. A class can now use all
the three visibility modes asillustrated below: When a
protected member is inherited in public mode, it becomes
protected in the derived class too, and therefore is accessible
by the member functions of the derived class. It is also ready
What do you mean by polymorphism? How is the What is the difference between a function template and
polymorphism achieved at run time in C++? template function?
Answer: 1" Part: Polymorphism is one of the crucial features cout << average (c, n) ;
of OOP. It simply means "one name, multiple forms". It Answer: The term "function template" refers to a kind of
provides another dimension of separation of interface from template. The term "template function" is sometimes used to
implementation, to decouple what from how. Polymorphism mean the same thing, and sometimes to mean a function
allows improved code organization and readability as well as instantiated from a function template or class templare. This
the creation of extensible programs that can be "grown" not ambiguity is best avoided by using "function template" for
only during the original creation of the project, but also when the former and something like "function template instance"
new features are desired. At run time, when it is known what or "instance of a function template" for the latter. Note that a
class objects are under consideration, the appropriate function template is not a function. The same distinction
version of function is invoked. Since the function is linked applies to "class template" versus "template class".
with a particular class much later after the compilation, this
process is known as late binding. It is also known as dynamic b) How can templates increase the code reuse?
binding because the selection of the appropriate function is
done at run time dynamically. Dynamic binding requires use Answer: Templates is a new concept, which enables us to
of pointers to objects. define generic classes and functions and thus provides
2nd Part: C++ supports another important feature, known as support for generic programming. Generic programming is an
run time polymorphism. This can be achieved with the help approach where generic types are used as parameters in
of virtual functions. At run time, when it is known what class algorithms so that they work for a variety of suitable data
objects are under consideration, the appropriate version of types and data structures.
function is invoked. Since the function is linked with a
particular class much later after the compilation, this process It provide code re-use without compromising type safety.
is known as late binding. It is also known as dynamic binding That said, from my experience they are overused when
because the selection of the appropriate function is done at subclassing would make more sense. Generic programming is
run time dynamically. Dynamic binding requires use of harder for someone else to understand, so use
pointers to objects. templates sparingly.
What is the difference between ios formatting functions and What are syntax and semantics for a class template?
manipulators? Answer: The syntax of class template (sometimes called
Manipulations are functions specifically designed to be used parameterized type) is the keyword template, some template
in conjunction with the insertion (<<) and extraction (>>) parameters, then something that looks a lot like a class (or a
operations on stream objects, for example: cout << function) but is not a class (or function), called the template's
boolalpha; body. Rather, it is a cookie cutter to create a family of classes
They are still regular functions and can also be called as any (or functions). templan both the above examples, the
other function using a stream object as argument, for template parameter is T (the keyword 'class' is a necessary
example: boolalpha(cout); Now, manipulations are used to addition serving no useful purpose). When the template is
change ios formatting functions parameters on streams and instantiated, it gets an actual value for T, which is then
to insert or extract certain special characters. So, ios replaced in the body to create the actual class. A template
formatting functions support both stream input and output. object (or function) is instantiated by specifying an actual
type/class as the template parameter. When the body is a
function, it generates potential typesafe functions for all
possibly types/classes.