[go: up one dir, main page]

0% found this document useful (0 votes)
254 views14 pages

Oop Answers

Data members are variables declared within a class using fundamental or user-defined data types. Member functions are functions declared within the class, and can be defined either inside or outside the class definition. There are two types of members - private members, which can only be accessed within the class, and public members, which can be accessed within and outside the class. An object is an instance of a class that allocates memory at runtime. Objects are created by declaring a variable of a class type. This allocates memory and allows accessing class members via the dot operator.

Uploaded by

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

Oop Answers

Data members are variables declared within a class using fundamental or user-defined data types. Member functions are functions declared within the class, and can be defined either inside or outside the class definition. There are two types of members - private members, which can only be accessed within the class, and public members, which can be accessed within and outside the class. An object is an instance of a class that allocates memory at runtime. Objects are created by declaring a variable of a class type. This allocates memory and allows accessing class members via the dot operator.

Uploaded by

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

1. What are Data members?

Explain what are Member functions within a class,


and where in the code can they be defined?

 "Data Member" and "Member Functions" are the new names/terms for the members of a
class, which are introduced in C++ programming language.
The variables which are declared in any class by using any fundamental data types (like int,
char, float etc.) or derived data type (like class, structure, pointer etc.) are known as Data
Members.

And the functions which are declared either in private section or public section are known as
Member functions.
There are two types of data members/member functions in C++:
 Private members
 Public members

1) Private members
The members which are declared in private section of the class (using private access
modifier) are known as private members. Private members can also accessible within the
same class in which they are declared.

2) Public members
The members which are declared in public section of the class (using public access modifier)
are known as public members. Public members can access within the class and outside of the
class by using the object name of the class in which they are declared.
We can access the data members and member functions of a class by using a ‘.’ (dot)
operator.

class Test
{
private:
int a;
float b;
void getA ()
{
a=10;
}
public:
int count;
void getB ()
{
b=20;
}
};

There are 2 ways to define a member function:


 Inside class definition
 Outside class definition

2. How to implement a class? (Give the syntax)

 A class is defined in C++ using keyword class followed by the name of class. The body of
class is defined inside the curly brackets and terminated by a semicolon at the end.

class ClassName
{
Access Specifier; // can be private, public or protected

Data Members; // variables to be used

Member Functions; //Methods to access data members

}; //Class name ends with a semi- colon

3. What are objects? How to create an object?

 An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated. To use the data and access
functions defined in the class, we need to create objects.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an
object would be the variable. You can create multiple objects of one class.
Declaring Objects: When a class is defined, only the specification for the object is defined.
No memory or storage is allocated. To use the data and access functions defined in the class,
you need to create objects.
Syntax:
ClassName ObjectName;
4. What are the different ways of initializing a class’s members using an Object (implicit and
explicit)?

 Implicit - Default constructor


 Explicit - Parameterized constructor
(explained later)

Parameterized constructor syntax:

class class_name {

Access Specifier :
Member - Variables
Member - Functions
public:
class_name(variables) {
// Constructor code
}

//... other Variables & Functions


}

5. What is the use of the ‘this’ Pointer?

 Every object in C++ has access to its own address through an important pointer called this
pointer. The ‘this’ pointer is an implicit parameter to all member functions. Therefore, inside
a member function, this may be used to refer to the invoking object.
Friend functions do not have a ‘this’ pointer, because friends are not members of a class.
Only member functions have a ‘this’ pointer.
To understand ‘this’ pointer, it is important to know how objects look at functions and data
members of a class.

 Each object gets its own copy of the data member.


 All-access the same function definition as present in the code segment.

Meaning each object gets its own copy of data members and all objects share a single copy of
member functions.
The compiler supplies an implicit pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and
is available as a local variable within the body of all non-static functions. ‘this’ pointer is not
available in static member functions as static member functions can be called without any
object (with class name).
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

6. Define all OOP concepts with examples (case where it is used) [inheritance,
polymorphism, encapsulation, abstraction].
 Inheritance is one of the key features of Object-oriented programming in C++. It allows us to
create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have additional features of
its own.
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
 Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
 Super Class: The class whose properties are inherited by sub class is called Base Class or
Super class.
Implementing inheritance in C++: For creating a sub-class which is inherited from the base
class we have to follow the below syntax.
Syntax:

class subclass_name : access_mode base_class_name


{

//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you
want to inherit this sub class for example: public, private etc. and base_class_name is the
name of the base class from which you want to inherit the sub class.

 Public mode: If we derive a sub class from a public base class. Then the public member of
the base class will become public in the derived class and protected members of the base
class will become protected in derived class.
 Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
 Private mode: If we derive a sub class from a Private base class. Then both public member
and protected members of the base class will become Private in derived class.

 The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism, a person at the same time can have different characteristics. Like
a man at the same time is a father, a husband, an employee. So, the same person possesses
different behavior in different situations. This is called polymorphism. Polymorphism is
considered as one of the important features of Object-Oriented Programming.

In C++ polymorphism is mainly divided into two types:

 Compile time Polymorphism


 Runtime Polymorphism

 Data encapsulation is a mechanism of bundling the data, and the functions that use them and
data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. In normal terms Encapsulation is defined as wrapping up of
data and information under a single unit. In Object Oriented Programming, Encapsulation is
defined as binding together the data and the functions that manipulates them.
Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the
data.

 Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation. Class helps us to group data
members and member functions using available access specifiers. A Class can decide which
data member will be visible to outside world and which is not.
Advantages of Data Abstraction:
 Helps the user to avoid writing the low-level code.
 Avoids code duplication and increases reusability.
 Can change internal implementation of class independently without affecting the user.
 Helps to increase security of an application or program as only important details are provided
to the user

7. How to create a Constructor/Destructor?


A class constructor is a special member function of a class that is executed whenever we
create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at
all, not even void. Constructors can be very useful for setting initial values for certain
member variables.

A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope or whenever the delete expression is applied to a pointer to the object
of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can
neither return a value nor can it take any parameters. Destructor can be very useful for
releasing resources before coming out of the program like closing files, releasing memories
etc.

// Default Constructor

class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};

Or

class_name(parameter1, parameter2, ...)


{
// constructor Definition
}
Or
class A
{
public:
int i;
A(); // constructor declared
};

// constructor definition
A::A()
{
i = 1;
}

// Destructor

class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};

8. What are the types of Constructors? How do they differ from each other?
How does it differ from a function?
Constructors are of three types:

1. Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.

2. Parametrized Constructor
These are the constructors with parameter. Using this Constructor, you can provide different
values to data members of different objects, by passing the appropriate values as argument.

3. Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into another object. We will study copy constructors in
detail later.

Constructor vs function:
 Constructor name must be same as class name but functions cannot have same name as class
name.
 Constructor does not have return type whereas functions must have.
 Member function can be virtual, but there is no concept of virtual-constructor in C++.
 Constructors are invoked at the time of object creation automatically and cannot be called
explicitly but functions are called explicitly using class objects.

9. What is a friend function? How does it help us? Show with an example.
A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class


template, in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows –

class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}

A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class.
A simple example of C++ friend function used to print the length of a box.

class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}

10. How to overload a function (show 3 different ways)?

11. What are the rules involved while overloading an operator?


There are some rules for the operator overloading. These rules are like below

1. Only built-in operators can be overloaded. If some operators are not present in C++, we
cannot overload them.
2. The arity of the operators cannot be changed
3. The precedence of the operators remains same.
4. The overloaded operator cannot hold the default parameters except function call operator
“()”.
5. We cannot overload operators for built-in data types. At least one user defined data types
must be there.
6. The assignment “=”, subscript “[]”, function call “()” and arrow operator “->” these operators
must be defined as member functions, not the friend functions.
7. Some operators like assignment “=”, address “&” and comma “,” are by default overloaded.
12. What is Function overriding? Give a complete example of it.
Inheritance is a feature of OOP that allows us to create derived classes from a base class. The
derived classes inherit features of the base class.
Suppose, the same function is defined in both the derived class and the based class. Now if
we call this function using the object of the derived class, the function of the derived class is
executed.
This is known as function overriding in C++. The function in derived class overrides the
function in base class.

// C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

//Output:
Derived Function

Here, the same function print() is defined in both Base and Derived classes.
So, when we call print() from the Derived object derived1, the print() from Derived is
executed by overriding the function in Base

13. Define access specifiers


Access specifiers define how the members (attributes and methods) of a class can be
accessed.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the
class members. That is, it sets some restrictions on the class members not to get directly
accessed by the outside functions.
There are 3 types of access modifiers available in C++:
 Private
 Public
 Protected

14. Name the different types of access modes along with an explanation.
1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed by
other classes and functions too. The public members of a class can be accessed from
anywhere in the program using the direct member access operator (.) with the object of that
class.
2. Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of a class.
3. Protected: Protected access modifier is similar to private access modifier in the sense that it
can’t be accessed outside of its class unless with the help of friend class, the difference is that
the class members declared as Protected can be accessed by any subclass(derived class) of
that class as well.

15. What is the Diamond Inheritance Problem? What can be done to overcome?
it? (Give complete code example)
The diamond problem occurs when two super classes of a class have a common base class.
The "diamond problem" is an ambiguity that arises when two classes B and C inherit from A,
and class D inherits from both B and C.

#include<iostream>
using namespace std;
class Person {

public:
Person(int x)
{ cout << "Person::Person(int ) called" << endl; }
};

class Faculty : public Person {


// data members of Faculty
public:
Faculty(int x):Person(x) {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
};

class Student : public Person {


// data members of Student
public:
Student(int x):Person(x) {
cout<<"Student::Student(int ) called"<< endl;
}
};

class TA : public Faculty, public Student {


public:
TA(int x):Student(x), Faculty(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
}

In the above program, constructor of ‘Person’ is called two times. Destructor of ‘Person’ will
also be called two times when object ‘ta1’ is destructed. So object ‘ta1’ has two copies of all
members of ‘Person’, this causes ambiguities.

The solution to this problem is ‘virtual’ keyword. We make the classes ‘Faculty’ and
‘Student’ as virtual base classes to avoid two copies of ‘Person’ in ‘TA’ class. For example,
consider the following program.

16. Define ‘virtual’ keyword. In what circumstance is it used? How does it


differ from a normal inherited function?
A virtual keyword in C++ is used to create a virtual function in C++. The virtual function is
the parent class function which we want to redefine in the child class. The virtual function is
declared by using the keyword virtual. When we define the virtual function the keyword
virtual is to be proceeding in the declaration of the function.
The single pointer is required to refer to all objects of different classes. Therefore, the pointer
is created on the superclass to refer all the objects of the derived class and then the superclass
pointer contains the address of the object of the derived class always run the superclass
function. So, to resolve this we use the ‘virtual’. So, when the virtual function is created in
the superclass then the C++ compiler identifies which function is to be executed at run time
and the identification of the function takes based on the type of object the superclass pointer
pointing. A virtual keyword in C++ is used to create a virtual function in C++.
The virtual function is the parent class function which we want to redefine in the child class.
The single pointer is required to refer to all objects of different classes. The superclass
pointer contains the address of the object of the derived class always run the superclass
function. The Virtual functions must be class members, must be class members, cannot be
declared as static, accessed through object pointers. The signature of a virtual function of the
superclass and the child classes should be the same, so-called as function overriding, else if
the two functions with the same name but different signature, it is considered as the
overloaded functions in C++

17. What is a Pure Virtual Function? How does it differ from a normal Virtual function?
The virtual function and pure virtual function both are the concepts of run time
polymorphism. The main difference between ‘virtual function’ and ‘pure virtual function’ is
that ‘virtual function’ has its definition in the base class and also the inheriting derived
classes redefine it.
The pure virtual function has no definition in the base class, and all the inheriting derived
classes has to redefine it. However, the virtual function is also called as dynamic dispatch and
run-time dispatch, due to the function called is specified in the run time in accordance with
the type of the object used.
Virtual functions are hierarchical in nature; it does not affect compilation if any derived
classes do not override the virtual function of the base class.
In pure virtual functions if all derived classes fail to override the virtual function of the base
class, the compilation error will occur and derived class also becomes abstract just like the
base class.

18. What is the difference between a conventional class and an abstract class?
How to access abstract classes
A class is a construct that enables you to create your own custom types by grouping together
variables of other types, methods and events. A class is like a blueprint. It defines the data
and behavior of a type. If the class is not declared as static, client code can use it by creating
objects or instances which are assigned to a variable. The variable remains in memory until
all references to it go out of scope. At that time, the CLR marks it as eligible for garbage
collection. If the class is declared as static, then only one copy exists in memory and client
code can only access it through the class itself, not an instance variable.

Abstract classes, marked by the keyword abstract in the class definition, are typically used to
define a base class in the hierarchy. What's special about them, is that you can't create an
instance of them - if you try, you will get a compile error. Instead, you have to subclass them,
and create an instance of your subclass.
// An abstract class
class ClassName
{
// Data members of class
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes
// this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.

void NonAbstractMemberFunction2();
};

A class is abstract if it has at least one pure virtual function. We can have pointers and
references of abstract class type. If we do not override the pure virtual function in derived
class, then derived class also becomes abstract class. An abstract class can have constructors.
The classes inheriting the abstract class must provide a definition for the pure virtual
function; otherwise, the subclass would become an abstract class itself.

19. What is the main reason why abstract classes are created?
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate
base class from which other classes can inherit. Abstract classes cannot be used to instantiate
objects and serves only as an interface. Attempting to instantiate an object of an abstract class
causes a compilation error.

Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual
functions, which means that it supports the interface declared by the ABC. Failure to override
a pure virtual function in a derived class, then attempting to instantiate objects of that class, is
a compilation error.

Syntax for inheritance

class derived_class_name: public base_class_name


{

/*...*/

};

You might also like