0% found this document useful (0 votes)
129 views25 pages

Notes On OOP and MCQ On C

Object Oriented Programming (OOP) uses classes and objects to model the real world, making code easier to maintain and modify as new objects can inherit from existing ones. In contrast, Procedural Programming breaks tasks into sequential steps of variables and routines. OOP supports concepts like encapsulation, inheritance and polymorphism which make the code more secure and less complex to modify, unlike procedural code which is more difficult to enhance without revising the whole program.

Uploaded by

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

Notes On OOP and MCQ On C

Object Oriented Programming (OOP) uses classes and objects to model the real world, making code easier to maintain and modify as new objects can inherit from existing ones. In contrast, Procedural Programming breaks tasks into sequential steps of variables and routines. OOP supports concepts like encapsulation, inheritance and polymorphism which make the code more secure and less complex to modify, unlike procedural code which is more difficult to enhance without revising the whole program.

Uploaded by

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

Object Oriented Programming (OOP) Procedural Oriented Programming

(POP)

Definition Object-oriented Programming is a On other hand Procedural Oriented


programming language that uses Programming is a programming
classes and objects to create models language that follows a step-by-
based on the real world environment. In step approach to break down a
OOPs it makes it easy to maintain task into a collection of variables
and modify existing code as new and routines (or subroutines)
objects are created inheriting through a sequence of
characteristics from existing ones. instructions. Each step is carried out
in order in a systematic manner so
that a computer can understand what
to do.

Approach In OOPs concept of objects and classes On other hand in case of POP the the
is introduced and hence the program is main program is divided into small
divided into small chunks called objects parts based on the functions and is
which are instances of classes. treated as separate program for
individual smaller program.

Access In OOPs access modifiers are On other hand no such modifiers


modifiers introduced namely as â~PrivateâTM, are introduced in POP.
â~publicâTM, and âTM~ProtectedâTM.

Security Due to abstraction in OOPs data On other hand POP is less secure
hiding is possible and hence it is as compare to OOPs.
more secure than POP.

Complexity OOPs due to modularity in its programs On other hand thereâTMs no simple
is less complex and hence new data process to add data in POP at least
objects can be created easily from not without revising the whole
existing objects making object-oriented program.
programs easy to modify
Chracteristics of OOP:
 Encapsulation/Data Hiding
 Inheritance
 Polymorphism
 Abstraction
 All predefined types are objects
 All user defined types are objects
 All operations performed on objects must be only through methods
exposed at the objects.

C++ OOP
1. Objects:
An object is an instance of a Class. A class occupies no memory unless it
instantiated, i.e. and object are created.
2. Class:
A class in C++ is a user-defined type or data structure declared with
keyword class that has data and functions as its members whose access
is governed by the three access specifiers private, protected or public. By
default, access to members of a C++ class is private.

OOP Examples in C++


1. Abstraction
Data abstraction refers to, providing only essential information to the
outside world and hiding their background details.
a. Abstraction using Classes: 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.
b. Abstraction in Header files: One more type of abstraction in C++
can be header files. For example, the pow() method present in
math.h header file.
Real World Example of Abstraction-
When we ride a bike, we only know about how to ride bikes but
cannot know about how it works? And also, we do not know the
internal functionality of a bike.
2. Encapsulation:
Defined as wrapping up of data and information under a single unit. In
OOP, Encapsulation is defined as binding together the data and the
functions that manipulates them.
In C++ encapsulation can be implemented using Class and access
modifiers.

3. Polymorphism:
The ability to use an operator or function in different ways in other
words giving different meaning or functions to the operators or
functions is called polymorphism. E.g.:

a. Function Overloading
class Geeks

{
public:

void func(int x){


cout << "value of x is " << x << endl;
}

void func(double x){


cout << "value of x is " << x << endl;
}

void func(int x, int y){


cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main() {

Geeks obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85,64);
return 0;

b. Operator Overloading
using namespace std;
   
class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}
       
    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};
   
int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

c. Function Overriding
class base
{
public:
    virtual void print ()
    { cout<< "print base class" <<endl; }
   
    void show ()
    { cout<< "show base class" <<endl; }
};
   
class derived:public base
{
public:
    void print ()
    { cout<< "print derived class" <<endl; }

/*Can also be written as:


void print () override
    { cout<< "print derived class" <<endl; }

*/
   
    void show ()
    { cout<< "show derived class" <<endl; }
};
  
int main() 
{
    base *bptr;
    derived d;
    bptr = &d; //implemented using Dynamic Dispatch
       
    
    bptr->print();  //OutPut-> "print derived class"
       
    
    bptr->show();  //OutPut-> "show base class”
  
    return 0;
}
 

4.

Inheritance:
The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important features 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.

a. Single Level b. Multiple Inheritance

c. Multilevel Inheritance d. Hierarchical Inheritance


e. Hybrid

Modes of Inheritance:

Friend class and function in C++

Friend Class A friend class can access private and protected members of other
class in which it is declared as friend. 
It is sometimes useful to allow a particular class to access private members of
other class.
class Node {
private:
    int key;
    Node* next;
    /* Other members of Node Class */
  
    // Now class  LinkedList can
    // access private members of Node
    friend class LinkedList;
};
Friend Function Like friend class, a friend function can be given special grant to
access private and protected members. A friend function can be:
a) A method of another class
b) A global function
class Node {
private:
    int key;
    Node* next;
  
    /* Other members of Node Class */
    friend int LinkedList::search();
    // Only search() of linkedList
    // can access internal members
};

Constructors in C++
A constructor is a member function of a class which initializes objects of a
class. In C++, Constructor is automatically called when object(instance of class)
create. It is special member function of the class.
A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).

Default Constructors: Default constructor is the constructor which doesn’t


take any argument. It has no parameters.

Parameterized Constructors: It is possible to pass arguments to constructors.


Typically, these arguments help initialize an object when it is created. To create
a parameterized constructor, simply add parameters to it the way you would
to any other function. 

Copy Constructor: A copy constructor is a member function which initializes an


object using another object of the same class.
class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1) { x = x1; y = y1; }
  
    // Copy constructor
    Point(const Point &p2) {x = p2.x; y = p2.y; }
  
    int getX()            {  return x; }
    int getY()            {  return y; }
};
  
int main()
{
    Point p1(10, 15); // Normal constructor is called here
    Point p2 = p1; // Copy constructor is called here
  
    // Let us access values assigned by constructors
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
  
    return 0;
}

Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

Destructors
Destructor is a member function which destructs or deletes an object.
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called 
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
class String
{
private:
    char *s;
    int size;
public:
    String(char *); // constructor
    ~String();      // destructor
};
 
String::String(char *c)
{
    size = strlen(c);
    s = new char[size+1];
    strcpy(s,c);
}  
String::~String()
{
    delete []s;
}
Details about Polymorphism and Virtual Functions
Let’s look at the following code-
What are Virtual Functions?
class Base {
public: A virtual function is a member function which is
    virtual void show()
    { declared within a base class and is redefined
        cout << " In Base \n";
    } (Overriden) by a derived class. 
};
   In this code, we want the function showAns to
class Derived : public Base { know which function (“show”) to call, with
public:
    void show() respect to the type of object.
    {
        cout << "In Derived \n"; There is no problem when we pass Base type
    }
}; object.
Void showAns(Base *obj){
cout<<obj->show; The problem may arise for the Derived class
}
   type object. Even though it is inheriting from
int main(void) Base class, somehow out function “showAns” is
{
    Base* bp = new Base; not able to print “In Derived”.
showAns(bp);
Derived* d = new Derived; To solve this, we use Virtual Functions.
   showAns(d);
return 0;
}

Pure Virtual Functions and Abstract Classes and Interfaces in C++


A pure virtual function (or abstract function) in C++ is a virtual function for
which we don’t have implementation, we only declare it. A pure virtual
function is declared by assigning 0 in declaration.
// An abstract class
class Test
{   
    // Data members of class
public:
    // Pure Virtual Function
    virtual void show() = 0;
    
   /* Other members */
};

A class is abstract if it has at least one pure virtual function.


Interface class with nothing but just pure virtual functions.
Abstract classes cannot be used to instantiate objects and serves only as
an interface. 

1. We can have pointers and references of abstract class type.


2. An abstract class can have constructors.
3. An abstract class can’t be instantiated.

Exception Handling in C++


Exceptions are run-time anomalies or abnormal conditions that a program encounters during
its execution. There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which
are beyond the program’s control, Disc failure etc). 

C++ provides following specialized keywords for this purpose.


try: represents a block of code that can throw an exception.

catch: represents a block of code that is executed when a particular exception is


thrown.

throw: Used to throw an exception. Also used to list the exceptions that a function
throws, but doesn’t handle itself.
int main()
Types of Exceptions in C++
{
   int x = -1;
  
   // Some code
   cout << "Before try \n";
   try {
      cout << "Inside try \n";
      if (x < 0)
      {
         throw x;
         cout << "After throw (Never executed) \n";
      }
   }
   catch (int x ) {
      cout << "Exception Caught \n";
   }
  
   cout << "After catch (Will be executed) \n";
   return 0;
}
C Program Revision

1.
int main(){
int arr[5];
arr++;
printf(“%u”,arr);
return 0;
}

A. 2002 B.2004
B. 2020 D. lvalue required

Why?
1. arr[] and arr[0] means the same
2. In this we are incrementing the address, and not moving onto the next element.
Hence, we get an error.

2.
int main(){
int arr[5];
//assume base address to be 2000
printf(“%u %u”,arr+1,&arr + 1)
return 0;
}

A. 2004 2020 B.2004 2004


C. 2004 Garbage D. Error
Why?
1. &arr is the address of the whole array. i.e. last element address
3.
void print(int arr[]){
int n = sizeof(arr)/sizeof(arr[0]);
int i;
for(i=0;i<n;i++)
printf(“%d”,arr[i]);
}
int main(){
int arr[]={1,2,3,4,5};
print(arr);
return 0;
}

A. 1 2 3 4 5 6 7 8 B. Compiler Error C.1 2 D. Run Time Error

Why?
1. In print(arr) we send the pointer, and not the array. Hence sizeof(arr) in the function
print() results in the size of pointer which is 4.
If we wrote sizeof(arr) in main, then it would result in 32(i.e 8x4)

4.
#include<stdio.h>
int main(int argc, char const *argv[])
{
char arrp[100];
printf("%d",scanf("%s",arr)); //Assume input =”sanjay”
return 0;
}
A. 5 B.1 C.Error D.0
Why?
1.scanf() returns the number of arguments read.

5.
int main(int argc, char const *argv[])
{
int a[][] = {{1,2},{3,4}};
int i,j
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
printf("%d",a[i][j]);
}
}
return 0;
}

A. 1 2 3 4 B. Compiler Error C. 4 Garbage D.4 3 2 1}

Why?

1. arr[][] size is not defined. Works if arr[][M] or arr[][M][N] or arr[M]


6.
#include<stdio.h>
int main(int argc, char const *argv[])
{
int i;

int arr[5] = {1};


for (i = 0; i < 5; ++i)
{
printf("%d",arr[i]);
}
return 0;
}

A. 1 & Garbage Value B.1 0 0 0 0 C.Error D.1 1 1 1 1


Why?
1. It is because of C compiler design

7.
#include<stdio.h>
int main(int argc, char const *argv[])
{
printf(5+”Capgemini”)
return 0;
}

A. m B.mini C.1005 D.error


Why?
1.Pointer of printf() gets shifted by 5times.
8.
#include<stdio.h>
int main(int argc, char const *argv[])
{
printf(“%c”,5[“Capgemini”])
return 0;

A. mini B. m C.Error D.No output

9.

#include<stdio.h>
int main(int argc, char const *argv[])
{
int x;
for(x=-1;x<=10;x++){
if(x<5)
continue;
else
break;
printf(“abc”);
}
return 0;

}
A. Infinite times B.11 times C.0 times D.10 times

Why?
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.
10.

#include<stdio.h>
int main(int argc, char const *argv[])
{
int i;
for (; i <=5; ++i);
printf("%d",i);
return 0;
}

a. 0,1,2,3,4,5 b. 6 c.1,2,3,4 d.6

11.
#include<stdio.h>
int main(int argc, char const *argv[])
{
int a =500, b=100,c;

if(!a >= 400)


b=300;
c = 200;
printf("b=%d c=%d\n",b,c );
return 0;
}

A. b=300 c =200 B.b=100 c=garbage C.b=300 c=garbage D.b=100 c=200

Why?
First a>=400 is evaluated and then the result of it is complemented
12.

Why?
First we check, then increments ,i.e becomes 0. Since there is pre-increment it will output 1.
Next we check, then increments ,i.e becomes 2. Since there is pre-increment it will output 3.
Therefore infinite.

13.

Why?
Implicit conversion takes place in the condition.
14.

Why?
ch = 0, therefore goes to else. If ch was equall to anything else, it would have printed if part

15.
16.

17.

18.
19.
11.

Why?
0x10 is a hexadecimal, 010 is octal. All are converted to int/decimal.
In printf(), %x is hexadecimal.

20.
21.

Why?
printf() returns no of characters printed.Note that \0 is not there.

22.
23.

Why?
sizeof(a) = 12,since we include a null character
sizeof(p) = 2, since p is a pointer which stores an address of type int(could be 4 also)
strlen(a) = 11, we don’t include end character(\0)
strlen(p) = 11, from start of address till end character(excluded)

24.
25.

Why?
First we evaluate if(c>1). If not satisfy then 300.
Since its true, we go to next condition if(d>1 && e>1).If true then 100 else 200.

26.

You might also like