An instance of a class is called __________.
- Astructure
- Bdata type
- Cobject
- Dmember function
An object is a variable (instance) created from a class.
Syllabus: lectures 25–45. Past-paper MCQs are shown first.Syllabus: lecture 25–45. Past paper ki MCQs pehle dikhai gayi hain.
207 MCQs · 55 short · 32 long questions · 207 MCQs from past papers207 MCQs · 55 short · 32 long sawal · 207 MCQs past papers se
An instance of a class is called __________.
An object is a variable (instance) created from a class.
If a friend function outside the class declares itself friend of the class, this may violate the concept of ________.
Friendship must be granted by the class; a function granting itself access would break encapsulation and data hiding.
The prototype of friend function is written ________.
A friend declaration can appear anywhere in the class; access specifiers do not affect it.
Friend class of the other class gets ______ access to ______.
A friend class can access all private and protected members of the class that befriends it.
Which of the following statement is best regarding declaration of friend function?
Access specifiers do not affect friend declarations, so they may appear anywhere in the class.
Like member functions, ______ can also access the private data members of a class.
A friend function is granted access to the class's private members.
Friend function of a class is ______________ .
A friend function is not a member of the class even though it has access to it.
Function implementation of friend function must be defined outside the class.
A friend function can also be defined inline inside the class body.
The prototype of friend functions must be written ____ the class and its definition must be written ____
The friend declaration goes inside the class and the function is normally defined outside it.
A function can declare itself a friend of a class.
Friendship is granted by the class, not claimed by the function.
A friend function of a class has access
A friend can use all members of the class, including private and protected ones.
A friend function
A friend is not a member but is allowed to use the class's private data.
A ______ is considered as a special type of pointer which contains address of a memory location.
A reference is an alias implemented like a constant pointer that is automatically dereferenced.
Which of the following will be the correct function call for function prototype given below? int func (int &);
A reference parameter is passed the variable itself, so the call is func(num); &num would pass an int* and not compile.
If there is a symbol (& sign) used with the variable name followed by data type then it refers to _____ and if & is being used with variable name then it refers to _____.
In a declaration (int &r) & makes a reference; in an expression (&x) it takes the address.
We can do arithmetic with references like pointers.
A reference is an alias; arithmetic on it changes the referred value, not an address.
Which of the following function calling mechanism is true for the function prototype given below? float func(float &);
float & declares a reference parameter.
In functions that return reference, use __________variables.
Returning a reference to a local would dangle; global or static variables outlive the call.
To avoid dangling reference, always return the reference of a local variable from a function.
Returning a reference to a local variable creates a dangling reference.
We cannot increment ____________.
A reference is a fixed alias; ++ on it changes the referred variable, not the reference itself.
We can _____________references.
A reference is bound once at initialization and cannot be reseated or moved.
When we define an array of objects then ______________.
Each element of an array of objects is a separate object, so the constructor runs once per element.
When an array of object is created dynamically then there is no way to provide parameterized constructors for array of objects.
With new Class[n] (classic C++) each element is built with the default constructor.
If text is a pointer of class String then what is meant by the following statement? text = new String [5];
new String[5] allocates five String objects on the free store at run time.
We can also create an array of user define data type.
Arrays of structures or class objects are allowed.
When we define an array of objects then,
Every object in the array is destroyed separately, so the destructor runs once per object.
In C/C++, ________ are the doors through which data can enter and come out of a program.
Streams are the channels through which data flows into and out of a program.
The normal source of cin object is ________.
cin is the standard input stream, normally connected to the keyboard.
The input/output streams cin and cout are ________ therefore have _______.
cin and cout are stream objects, so they have member functions such as get() and put().
For cin, the source is normally a ________ and destination can be ______.
cin reads from the keyboard into an ordinary variable.
A stream is an ordered sequence of bytes.
A stream is a sequence of bytes flowing in order.
The input/output streams; cin and cout are ____
cin and cout are stream objects (of istream and ostream).
Both endl and flush are ________.
endl and flush are stream manipulators that act on the output stream.
What will be the output of the following statement? cout << setbase(16) << 52 ;
setbase(16) prints in hexadecimal and 52 decimal is 0x34.
Which header file should be included in the program to use stream manipulators?
Parameterized manipulators such as setw and setprecision are declared in iomanip.h.
width() is member function of _____________
width() is a member of the ios base class, so both input and output streams have it.
When we use manipulators in our program then which header file should be included?
Parameterized manipulators are declared in iomanip.h.
setprecision is a parameter less manipulator.
setprecision takes an argument, so it is a parameterized manipulator.
setw is a parameterized manipulator.
setw takes a width argument.
dec, hex, oct are all __________
dec, hex and oct take no arguments.
The return type of the operator function for << operator is ________.
operator<< returns ostream& so that insertions can be chained.
The stream insertion and stream extraction operators are already overloaded for ________.
The library overloads << and >> for built-in types; user-defined types need their own overloads.
The stream insertion and extraction operators ____________.
The left operand is a stream object, not the user's class, so << and >> for a user class are overloaded as non-member (usually friend) functions.
The first parameter of operator function for << operator,
The ostream argument cannot be copied, so it is taken by reference.
The second parameter of operator functions for << and >> are objects of the class for which we are overloading these operators.
The stream comes first and the class object second, e.g. ostream& operator<<(ostream&, const T&).
The first parameter of overloaded stream insertion operator is _________ where second parameter is _______
operator<< takes the ostream first and the class object second.
The operator function of << and >> operators are always the member function of a class.
Stream operators are normally non-member (often friend) functions since the stream is the left operand.
We can also define a user-defines manipulators.
C++ lets programmers write their own manipulators.
A constructor will create a new object with a full copy of the other object, this type of copy is known as ________.
A deep copy duplicates the pointed-to data too, giving a full independent copy.
In statement Matrix m2 = m1 ;
m2 is being created and initialized from m1 in its declaration, which calls the copy constructor, not operator=.
Assignment operator is used to initialize a newly declared object from existing object.
Initializing a new object from an existing one uses the copy constructor, not the assignment operator.
The compiler does not provide a copy constructor if we do not provide it.
The compiler generates a default member-wise copy constructor when none is written.
The default copy constructor provides member wise assignment.
The compiler-generated copy constructor copies each member.
A copy constructor
A copy constructor builds a new object as a copy of an existing object of the same class.
A template function must have at least ________ generic data type.
A function template needs at least one template type parameter.
With template function, the compiler automatically detects the ______ and generates ______ using passed data.
The compiler checks the type of the passed data and generates a new instance of the function for it.
With template function, the compiler automatically detects the passed data and generates a new copy of function using passed data.
The compiler deduces the argument types and instantiates a matching function.
A template function can have different type of arguments.
A function template may use several generic types and ordinary types as parameters.
A template function must have only generic data types.
A function template can mix generic and ordinary parameter types.
The template functions do NOT promote the code reuse
Templates let one definition work for many types, which promotes reuse.
Template class cannot have static variables.
Class templates can have static members; each instantiation gets its own copy.
When we write a class template the first line must be:
A class template begins with template <class T>, where T is a type parameter name.
What will be the output of the following statement? cout << setfill('0') << setw(7) << 128 ;
The field is 7 wide and right-justified by default, so 4 fill zeros come before 128.
The stream insertion and extraction operators are not already overloaded for _______
<< and >> already work for built-in types; for user-defined types we must overload them.
Template functions can also be overloaded
Function templates can be overloaded with different numbers or types of parameters.
We can also define a variable of user define data type (object) as static.
Objects, like built-in variables, can be declared static.
If a class A declares itself a friend of class B and a class B declares itself a friend of class C then
Friendship is not transitive; A becomes a friend of C only when C grants it.
When memory for a program is allocated at run time then it is called ________
Allocation done while the program runs is dynamic memory allocation.
The following prototype of unary operator function indicates that it is ____________ . Date operator++(int )
The dummy int marks post-increment, and with no object parameter it must be a member function.
If we do not indent the code properly it will __________________
Indentation only affects readability; the compiler ignores it.
Static memory allocation is also known as ____________
Static memory is fixed when the program is compiled.
We can use New keyword inside of Class Constructor.
Constructors often allocate memory with new.
Deleting an array of objects without specifying [] brackets may lead to memory leak
Without [] only one destructor is called, so memory held by the other objects may leak.
When an operator function is define as member function then operand on the left side of operator must be an object.
A member operator is called on its left operand, which must be an object of the class.
Every data member or function inside the structure is ___ by default whereas everything declared inside a class is ____ by default.
Structure members are public by default; class members are private by default.
Which of the following is true for the C++ statement given below? int &ref = val ;
A reference is another name (alias, synonym) for an existing variable.
The input/output streams cin and cout are ________ therefore have _______.
cin and cout are stream objects, so they have member functions such as get() and put().
Consider the following code segment. class M { public: M &operator+(const M &); ... }; p + q //code of line implies that p.operator+(q) ... Let assume if p and q are class objects then function is implemented as _______
operator+ is declared inside the class with one parameter and called as p.operator+(q).
The dynamic memory allocation uses memory from the ________.
Dynamically allocated memory comes from the heap (free store).
When a value is referred by a normal variable then it is known as ________.
Using the variable name directly is direct reference; access through a pointer is indirect reference.
The operator used for casting in C is standard ________ operator.
C uses the cast operator (type) to convert a value to another type.
new operator allocates memory from free store and returns ________.
new returns a pointer to the allocated memory.
The pointer returned by the new operator points to ________ of memory chunks allocated by the new operator.
new returns the starting (first) address of the allocated block.
What does STL stand for?
STL is the C++ Standard Template Library.
The appropriate data type to store the number of rows and colums of the matrix is ________.
Row and column counts are whole numbers, so int is appropriate.
By using objects as class members, ________ is achieved.
Using existing class objects as members (composition) reuses existing code.
________ data members of a contained object can be accessed from inside of the containing class.
The containing class is not a friend or derived class, so it can access only the public members of the contained object.
When an object of a class is defined inside an other class then ________.
Member objects are constructed before the body of the enclosing class constructor runs.
The order of destruction of an object is ________.
Objects are destroyed in the reverse order of their construction.
________ is the only operator that the compiler overloads for user defined data type.
The compiler supplies a default member-wise assignment operator for classes.
A class member function defined for overloading a unary operator takes how many arguments ?
For a member unary operator the single operand is the calling object, so no argument is passed.
The region of memory, available for allocation at run time in C language is called ________ memory whereas in C++, is called ________.
C calls run-time allocatable memory the heap; C++ calls it the free store.
Which one of the given options is correct prototype syntax for overloaded operator?
The form is return-type operator symbol(parameters), e.g. int operator+(int).
The declarator of Plus (+) member operator function is ________.
A binary member operator+ returns the class type and takes the right-hand operand as its one parameter.
Sequence of event(s) when allocating memory using new operator is ________.
new first obtains memory and then runs the constructor on that memory.
Whenever we allocate any memory from the ________ then starting position of the block of the memory allocated is returned as an address that is kept in a pointer.
Dynamic allocation takes memory from the heap and returns its starting address.
Whenever we allocate any memory from the heap then starting position of the block of the memory allocated is returned as a ________ that is kept in a pointer.
The start of the allocated block is returned as an address, which is stored in a pointer.
Constructor is a special function, called whenever we instantiate a ________ of a class.
Instantiating an object of a class automatically calls its constructor.
Using a segment of source code again by adding new functionalities with slight or no modification is termed as ______.
Reusing existing code with little or no change is code reusability.
In windows operating system, function calling is like sending a/an ______ to the object.
In Windows (and OOP terms) calling a function on an object is described as sending it a message.
The static data members of a class will be ______.
A static data member has one copy that all objects of the class share; it is defined/initialized outside the class.
Which of the following option is true about static data members of a class?
Static data members follow normal access rules and can be declared private or public.
When a variable is defined as static in a class then ______.
A static class member exists once per class, shared by all objects.
Which of the following operator the compiler overloads for objects by default?
The compiler supplies a default assignment operator that copies members.
Templates provide way of abstracting ______ information.
Templates let code be written independent of the data type.
Classes defined inside other classes are called ______ classes
A class declared inside another class is a nested class.
If we write a statement like s2 = s1; ______ will be the calling object and ______ will be passed to the = operator as an argument.
The left operand s2 calls operator= and the right operand s1 is the argument.
We can use cin.peek() function to ______.
peek() returns the next character in the input stream without extracting it.
new and delete are also used with ______ and primitive data types as well.
new and delete work with class and structure objects as well as built-in types.
Memory allocated at run time is a system resource and it is the responsibility of ______ to de-allocate the memory.
Dynamically allocated memory must be freed by the programmer with delete/free.
While overloading new and delete operators, we should take care that ______.
Overloading new/delete for a specific class avoids affecting every allocation in the program.
A constructor has the same name as that of ______.
A constructor is named exactly like its class.
The destructor for all the objects in the program is automatically called when ______.
At program termination, destructors of remaining (static/global) objects run automatically.
When an argument is passed by reference, ____.
With pass by reference the function works directly on the caller's original variable, not a copy.
The member functions of a class occupy ____ region in memory for ____ object(s) of class.
Only one copy of member function code exists and is shared by all objects; only data members are per object.
The static data members of a class are initialized ____.
A non-const static data member is declared in the class but defined and initialized outside it at file scope.
The static data members of a class can be accessed by ____.
A public static member can be reached with the class name (ClassName::member) or through any object.
Static variable which is defined in a function is initialized ____.
A static local variable is initialized only once and keeps its value between calls.
The code is written to ____ the program.
Writing code is the implementation step of developing a program.
The initializer list is used to initialize the contained objects of a class at ____.
The member initializer list runs when the containing object is constructed, before the constructor body.
Which is NOT a protection level provided by classes in C++?
C++ access specifiers are only public, private and protected; there is no 'hidden'.
What should be the return type of the constructor?
A constructor has no return type, not even void.
Which of the following function cannot be overloaded?
A destructor takes no arguments, so a class can have only one and it cannot be overloaded.
Users must not know about ____.
Data hiding keeps how the methods work inside the class away from the users; they only use the public interface.
Consider the following code segment. class M { public: M &operator+(const M &); ... }; p + q //code of line implies that p.operator+(q) ... Let assume if p and q are class objects then function is implemented as ____.
p + q becoming p.operator+(q) means the operator is a member function called on the left operand.
Sequence of event(s) when deallocating memory using delete operator is ____.
delete first calls the object's destructor and then frees its memory.
Whenever new operator is called to create an object, the ____ is also called for that object.
new allocates memory and then calls the constructor to initialize the object.
The purpose of using cout<< is to __________.
cout is the standard output stream, normally the screen.
Which header file should be included to use functions like malloc() and calloc()?
malloc, calloc, realloc and free are declared in stdlib.h (cstdlib).
The programs in which we allocate static memory run essentially on ________.
Statically declared (automatic) variables are allocated on the stack; dynamic memory comes from the heap/free store.
TWAIN stands for _________.
TWAIN is commonly expanded as Technology Without An Interesting Name.
Which of the following is true while overloading operators?
Operator overloading cannot invent new operators, nor change precedence, associativity or arity.
Which of the following is true about operator overloading?
An overloaded operator accepts whatever operand types its parameter list declares, so it can mix objects and built-in types.
ANSI stands for _________.
ANSI is the American National Standards Institute.
Which of the following option will be true, if we overload "-=" operator?
Overloading - and = does not give you -=; the compound operator must be overloaded separately.
In operator overloading, a non-member unary operator function takes _______ arguments.
A non-member function has no implicit this, so its single operand is passed as one argument.
Which of the following statement is true about Assignment operator (=) and output stream 'cout'?
a = b = c groups right to left, while cout << x << y groups left to right.
If text is a pointer of class String then purpose of statement below is to __________. text = new String [5];
new String[5] allocates an array of five String objects on the heap at run time.
Which value is returned by the destructor of a class?
Destructors have no return type and return nothing.
(*this) represents ________.
this points to the object the member function was called on, so *this is that current object.
Which one of the following is the declaration of overloaded pre-increment operator implemented as member function?
Prefix ++ as a member takes no parameters; the dummy int parameter marks postfix.
Class is a user defined___________.
A class defines a new user-defined data type.
Which of the following is the correct C++ syntax to allocate space dynamically for an array of 10 int?
new int[10] allocates an array of 10 ints; new int(10) allocates one int initialized to 10.
Operator overloading can be performed through__________________.
An operator is overloaded by writing an operator function.
Which of the following function is used to increase the size of already allocated memory chunk?
realloc resizes a previously allocated memory block.
Overloaded delete operator function takes the same parameter as an argument returned by new operator function.
operator delete receives the pointer that operator new returned.
We can not define a function as a friend of a Template class.
Class templates can have friend functions and friend function templates.
new and delete are _____ whereas malloc and free are _____.
new/delete are C++ operators; malloc/free are C library functions.
Which situation would require the use of a non-member overloaded operator?
A member operator needs a class object on the left, so a built-in left operand requires a non-member.
When ever dynamic memory allocation is made in C/C++, it is freed_____________.
Dynamically allocated memory must be released explicitly with free or delete.
Which of the following function do NOT initialize the chunk of memory to all zero?
malloc leaves memory uninitialized while calloc zero-fills it.
The function free() returns back the allocated memory got thorough calloc and malloc to _____ .
calloc and malloc allocate from the heap, and free returns memory there.
Templates are not type safe.
Template types are known at compile time, so the compiler type-checks them.
A Matrix can be composed of ints, floats or doubles as their elements. Best way is to handle this, _______________
A class template handles all element types with one definition.
eof( ), bad( ), good( ), clear( ) all are manipulators.
These are stream-state member functions, not manipulators like endl or setw.
Which kind of functions can access private member variables of a class?
All member functions (private or public) and friends can access private members.
The return type of operator function must always be void.
Operator functions may return any type, such as a reference or an object.
Heap is constantly changing in size.
The heap grows and shrinks as memory is allocated and freed at run time.
While calling function, the arguments are assigned to the parameters from _____________.
Arguments are matched to parameters by position starting from the left.
Classes defined inside other classes are called ________ classes
A class declared inside another class is a nested class.
Every class contains _______________.
If not written, the compiler supplies a default constructor and destructor.
Structured Query Language is used for ______________
SQL is the language for querying and managing relational databases.
When a call to a user-defined function finishes, the variable defined inside the function is still in existence.
Local (automatic) variables are destroyed when the function returns.
The precedence of an operator can be changed through operator overloading.
Overloading cannot change an operator's precedence, associativity or arity.
"delete" operator is used to return memory to free store, which is allocated by the "new" operator.
delete releases memory obtained with new back to the free store.
Within the statement obj1=obj2; obj1 will call the assignment operator function and obj2 will be passed as an argument to function.
obj1 = obj2 becomes obj1.operator=(obj2).
Unary operator implemented as member function takes ____ arguments whereas non-member function takes _____ arguments.
A member gets its operand via this, so it takes none; a non-member takes the operand as one argument.
The statement cin.get (); is used to,
cin.get() with no arguments extracts a single character from standard input.
When we do dynamic memory allocation in the constructor of a class, then it is necessary to provide a destructor.
A destructor is needed to delete memory the constructor allocated, or it leaks.
Overloaded new operator function takes parameter of type size_t and returns
operator new has the signature void* operator new(size_t).
The default value of a parameter can be provided inside the ________________
A default argument can be given in either the prototype or the definition, but not repeated in both.
What purpose do classes serve?
Classes give encapsulation, real-world modeling and reuse together.
new operator is used to allocate memory from the free store during
new allocates memory dynamically while the program runs.
When an object of a class is defined inside another class then,
Destruction reverses construction: the enclosing destructor runs first, then the member objects' destructors.
It is possible to define a class within another class.
C++ supports nested classes.
New and Delete are also used with ___________ and data types as well.
new and delete create and destroy class objects as well as built-in types.
When new operator is overloaded at global level then corresponding built-in new operator will not be visible to whole of the program.
A global operator new replaces the built-in one for the whole program.
The operator function overloaded for an Assignment operator (=) must be
C++ requires operator= to be a non-static member function.
Constructors can not be overloaded like ordinary functions.
Constructors can be overloaded with different parameter lists, just like ordinary functions.
When an operator function is defined as member function for a binary Plus (+) operator then the number of argument it take is/are.
A member binary operator receives the left operand through this, so it takes only one explicit argument.
We can not define a variable of user-defined data type in the class.
A class can contain data members whose type is another user-defined type (composition).
What is the sequence of event(s) when allocating memory using new operator?
new first obtains memory, then runs the constructor on that memory.
If overloaded plus operator is implemented as non-member function then which of the following statement will be true for the statement given below? obj3 = obj1 + obj2 ;
A non-member binary operator receives both operands as parameters.
With user-defined data type variables (Objects), self assignment can produce __________.
Self assignment compiles fine but can corrupt data (e.g. freeing memory before copying), a logical error.
In the member initializer list, the data members are initialized,
Members are always initialized in declaration order, regardless of the list order.
"new" and "delete" keywords are _____________ in C++ language.
new and delete are C++ operators (they can even be overloaded).
Disks are _______________ devices having access time of _________ milliseconds.
The course handout describes disks as electro-mechanical with about 7 ms access time.
We can not make a member function of a class as template function.
Member functions can themselves be templates.
Overloaded delete operator function takes parameter of void pointer and returns ________.
operator delete is declared as void operator delete(void*).
It is a way of reusing the code when we contain objects of our already written classes into a new class,
Composition reuses existing classes by containing their objects.
new and delete operators cannot be overloaded as member functions.
new and delete can be overloaded as class member functions.
Reusing the variables in program helps to save the memory
Reusing a variable instead of declaring new ones avoids extra memory allocation.
Which of the following option is true about new operator to dynamically allocate memory to an object?
new computes the size, allocates, constructs the object and returns a typed pointer.
For non-member operator function, object on left side of the operator may be
A non-member operator does not require its left operand to be an object of the class.
The operator function will be implemented as _____, if obj1 drive the - operator whereas obj2 is passed as arguments to - operator in the statement given below. obj3 = obj1 - obj2;
When the left operand drives the call, the operator is a member function of its class.
Automatic variable are created on ________.
Automatic (local) variables live on the stack.
Which of the following is a valid class declaration?
A C++ class declaration uses the class keyword and ends with a semicolon.
Which of the following object(s) will call the member operator function within the statement given below? obj1=obj2+obj3;
The left operand of + (obj2) invokes the member operator function.
We can delete an array of objects without specifying [] brackets if a class is not doing dynamic memory allocation internally.
Arrays allocated with new[] must always be released with delete[].
For binary member operators, operands on the ___________ drives (calls) the operation.
For a member operator function the left operand is the object whose member function is called.
The ________ is called automatically when an object destroys
The destructor runs automatically when an object goes out of scope or is deleted.
The destructor is used to ____________.
A destructor does clean-up such as releasing memory the object allocated.
___________data isn't accessible by non-member functions or outside classes.
Private members can be used only by the class's own member (and friend) functions.
Member functions of the class ________ main program.
Public member functions can be called from main through an object.
You cannot overload the _____________ operator
The conditional operator ?: is one of the operators C++ does not allow to be overloaded.
A function declaration has the same relationship to a function definition that
A declaration only announces the name and type; the definition is the thing itself, as with a variable declaration and the variable.
There is a class Student, Which one of the following is a valid destructor for this class.
A destructor is ~ClassName() with no return type and no parameters.
No MCQs match this filter.Is filter mein koi MCQ nahi.
What does getline() member function of cin stream do?
cin.getline(buffer, size, delimiter) reads characters (including spaces) into the character array buffer until size − 1 characters are read or the delimiter (default '\n') is found; the delimiter is removed from the stream and a '\0' is added at the end.
What will be the output of following code, if user input a number 123? int input ; cin >> oct >> input; cout << hex << input ;
123 is read as octal: 1×64 + 2×8 + 3 = 83 (decimal). 83 in hexadecimal is 5×16 + 3 = 0x53. Output: 53
What is memory leak?
A memory leak happens when memory is allocated dynamically (with new/malloc) but never freed, for example because the pointer to it is lost or overwritten. That memory cannot be used again while the program runs, so free heap memory keeps shrinking and the program can eventually run out of memory.
When we call calloc function to allocate memory and its return a NULL pointer what does it mean?
It means the allocation failed: the requested amount of memory (number of elements × element size) is not available on the heap as one contiguous block. The program should check for NULL before using the pointer and handle the error (e.g. show a message and exit).
How can we overcome the issue of dangling reference in a program?
A dangling reference refers to memory or an object that no longer exists (e.g. a reference to a local variable returned from a function, or to deleted memory). Avoid it by never returning a reference (or pointer) to a local/automatic variable, returning by value or referring only to objects whose lifetime is longer than the reference (static, global or caller-owned objects), and by not using references/pointers to memory after it has been deleted (set pointers to NULL after delete).
Write the operator overloading declaration for a stream extraction (>>) operator for an integer.
Generic form for a class (declared as friend inside the class): friend istream& operator>>(istream& input, ClassName& obj); For a class holding an integer, e.g. class Number { int n; ... }; friend istream& operator>>(istream& in, Number& num); // body: in >> num.n; return in;
Suppose an object of class A is declared as data member of class B. (i) The constructor of which class will be called first? (ii) The destructor of which class will be called first?
(i) Constructor of class A (the member object) is called first, then the constructor of B. (ii) Destructor of class B is called first, then the destructor of A (reverse order of construction).
What will be the output of the following code snippet? int x = 10; int &y = x; y+=5; cout << x;
15. y is a reference (alias) to x, so y += 5 changes x to 15.
Write a function named Sum which accepts an integer as argument. In the function use a static variable to add the values passed to it as arguments with each function call. In the end, display the sum of values passed as arguments.
#include <iostream> using namespace std; int Sum(int value) { static int total = 0; // keeps its value between calls total += value; return total; } int main() { Sum(5); Sum(10); int result = Sum(15); cout << "Sum of values = " << result << endl; // 30 return 0; }
Given is the code for nested classes. class First { public: class Second { public: void Display() { cout<<"inner Object called..."; } }; }; Write main() function to create an object of inner class and then call its function Display().
int main() { First::Second obj; // inner class is accessed through the outer class name obj.Display(); // prints: inner Object called... return 0; }
When memory is allocated dynamically using new operator within the constructor of class then what is an appropriate place to de-allocate the memory?
The destructor of the class. The destructor runs automatically when the object goes out of scope or is deleted, so calling delete (or delete[] for arrays) there frees the memory allocated in the constructor and prevents memory leaks.
How can we initialize an object which is declared as constant data member in another class?
A const data member (including a const object member) cannot be assigned in the constructor body; it must be initialized in the constructor's member initializer list, e.g. class Outer { const Inner obj; public: Outer(int v) : obj(v) { } };
What happens when we use new and delete operators?
new allocates memory of the required size from the free store (heap), calls the constructor for objects, and returns a pointer to the start of that memory. delete calls the destructor for the object and then returns the memory to the free store (use delete[] for arrays allocated with new[]).
Is it possible to define the following two functions having the same names, in the same program? Justify your answer. int func(int x, int y); int func(int &x, int &y);
Yes, both can be declared and defined, because int and int& are different parameter types, so they are valid overloads. However, a call with variables such as func(a, b) is ambiguous (both versions match equally well) and the compiler reports an error at that call. Only a call with non-lvalue arguments such as func(2, 3) resolves, to func(int, int). So in practice the pair is not usable for normal calls with variables.
Given lines of code are three important functions of a class Matrix, describe each in one line Matrix(int=0, int=0); Matrix(const Matrix &); ~Matrix();
Matrix(int=0, int=0); is the constructor with default arguments (rows and columns default to 0), so it also works as the default constructor. Matrix(const Matrix &); is the copy constructor; it creates a new Matrix as a copy of an existing one. ~Matrix(); is the destructor; it runs when the object is destroyed and frees any memory the object allocated.
Friendship in classes/functions is granted or taken? How it is granted or taken?
Friendship is granted, not taken. A class grants it by declaring the function or class as a friend inside its own definition with the friend keyword, e.g. friend void show(Account &); or friend class Bank;. An outside function or class cannot make itself a friend.
Write a C/C++ statement to print a floating point number 1.234 in a 9-digit field with preceding zeros.
cout << setfill('0') << setw(9) << 1.234; // needs #include <iomanip>; prints 00001.234
Write down the meaning of given below line of code, where m is an object of class Matrix. if( &m != this)
It checks for self-assignment: it compares the address of object m with the this pointer (address of the calling object). The body runs only if m is a different object, so an object is not assigned or copied onto itself (used in an overloaded assignment operator).
Identify and correct the error in the given code segment. main() { int val = 30; int &ref = val; &ref = &ref++; }
Error: &ref = &ref++; is invalid. &ref is the address of val, not a modifiable variable, so it cannot be assigned to; ref++ gives a temporary value whose address cannot be taken; and a reference cannot be made to refer to another variable after initialization. Correction: use the reference like a normal variable, e.g. int main() { int val = 30; int &ref = val; ref++; // val becomes 31 return 0; }
Write a simple program which uses the getline() member function of cin object for reading a string of 30 characters from the keyboard as long as the user presses ENTER key and display the result.
#include <iostream> using namespace std; int main() { char str[31]; cout << "Enter a string: "; cin.getline(str, 31); // reads up to 30 characters or until ENTER cout << "You entered: " << str << endl; return 0; }
Suppose we want to pass a variable by reference to a function and we also don't want the function to change the original value of that variable. How can we achieve this in C++?
Pass it as a constant reference, for example void show(const int &x);. The variable is not copied (it is passed by reference), but because the reference is const the compiler gives an error if the function tries to modify it.
Write the C++ code for the declaration of overloaded stream extraction(>>) and stream insertion(<<) operator for the object d of type Date.
class Date { // data members ... public: friend ostream &operator<<(ostream &os, const Date &d); friend istream &operator>>(istream &is, Date &d); };
Suppose we have a class Student which contains an object of class String as its data member. Now if we create an object of Student type then what will be the construction sequence of objects?
The contained String object is constructed first (its constructor runs), and then the Student constructor body runs. Destruction happens in reverse: the Student destructor runs first, then the String destructor.
Can we pass the first parameter of a stream extraction or stream insertion operator by value? If not then why?
No. The first parameter is the stream object (ostream/istream) and it must be passed by reference. Stream objects cannot be copied (their copy constructor is not accessible), the operator must work on and change the state of the actual stream (for example cout or cin), and it returns the same stream by reference so that calls can be chained, e.g. cout << a << b.
Is it possible using operator overloading to change the behavior of - (minus operator) on integers? Justify your answer.
No. Operators cannot be overloaded for built-in types only; at least one operand of an overloaded operator must be an object of a user-defined type (class/struct/enum). The meaning of - for int is fixed by the language, so it cannot be changed.
Consider the following code segment. What will be the output of the following code segment? class class1{ public: class class2{ public: class2(){ cout << "Calling default constructor of class2\n" ; } }; class1(){ cout << "Calling default constructor of class1\n" ; } } ; main(){ class1::class2 obj1; class1 obj2 ; }
Calling default constructor of class2 Calling default constructor of class1 obj1 is an object of the nested class class2, so its constructor runs first. obj2 is a class1 object; class1 only defines class2 as a nested type and has no class2 data member, so only the class1 constructor runs.
Define static variable also explain life time of static variable?
A static variable (declared with the keyword static, e.g. static int count = 0; inside a function) is allocated once in static memory instead of on the stack. It is initialised only once (to 0 by default if no initialiser), and it keeps its value between function calls. Lifetime: it exists from its first initialisation until the program ends, even though its scope (visibility) is still limited to the block or file where it is declared.
What do you know about run time error?
A run-time error occurs while the program is executing, after it has compiled successfully. The program tries to do something illegal or impossible, so it crashes or gives wrong results. Examples: division by zero, accessing an array outside its bounds, dereferencing a NULL or invalid pointer, running out of memory, or opening a file that does not exist without checking. The compiler cannot detect these; they are found by testing and prevented with checks (e.g. if (b != 0)).
What is limitation of the friendship between classes?
Friendship is granted, not taken, and it is limited: (1) it is one-way - if class A declares class B its friend, B can access A's private members but A cannot access B's; (2) it is not transitive - a friend of a friend is not a friend; (3) it is not inherited - derived classes of a friend are not friends. Friendship also weakens encapsulation, so it should be used sparingly.
What is the source and destination of cin?
For cin the source is the standard input device, normally the keyboard, and the destination is the program's variables (memory) into which the extraction operator >> stores the values.
Write the general syntax of allocating memory dynamically to an array using new operator?
data_type *pointer = new data_type[number_of_elements]; Example: int *iptr = new int[10]; The memory is released with delete [] pointer;
What is difference between Unary and binary operators and how they can be overloaded?
A unary operator works on one operand (e.g. ++, --, unary -, !); a binary operator works on two operands (e.g. +, -, *, /, ==). Both are overloaded with a function named operator followed by the symbol: return_type operator symbol (parameters). - Unary as member: no argument, e.g. Complex operator-(); as non-member/friend: one argument, e.g. friend Complex operator-(Complex); - Binary as member: one argument (the left operand is the calling object), e.g. Complex operator+(Complex c); as non-member/friend: two arguments, e.g. friend Complex operator+(Complex a, Complex b);
How many types of templates?
Two types: function templates (generic functions) and class templates (generic classes).
What will be the output of following function if we call this function by passing int 5? template <class T> T reciprocal(T x) { return (1/x); }
0. T is deduced as int, so 1/x is integer division: 1/5 = 0 (the real value 0.2 is truncated), and the function returns int 0.
Write the syntax of an operator function. (source: 'Operator function ka syntax')
return_type operator symbol (parameter_list) { // body } As a member of a class: return_type ClassName::operator symbol (parameters) { ... } Example: Complex Complex::operator+(Complex c) { Complex t; t.real = real + c.real; t.imag = imag + c.imag; return t; }
Write the syntax of overloading the post increment and pre increment operators.
Pre-increment (++obj): ClassName& operator++(); (or ClassName operator++();) Post-increment (obj++): ClassName operator++(int); - the dummy int parameter only distinguishes postfix from prefix.
Write something about testing in designing program?
Testing is a step of program design in which the programmer checks that the program produces correct results. A test plan with test cases (normal values, boundary values and invalid inputs) and their expected outputs should be prepared and the program run against them. Errors found are debugged and the tests repeated. It is a good idea for someone other than the programmer to test the program, since they will try inputs the programmer did not expect.
How many arguments a Unary Operator take? Can we make a binary operator as unary operator?
A unary operator works on one operand. When overloaded as a member function it takes no argument (the calling object is the operand); as a non-member/friend function it takes one argument. No - overloading cannot change the number of operands (arity) of an operator, so a binary operator cannot be made unary or vice versa. (Symbols such as + - * & already have separate unary and binary forms, each of which keeps its own arity.)
What are manipulators? Give one example.
Manipulators are special functions/objects inserted into (or extracted from) a stream with << or >> to change the format or state of the stream, e.g. width, precision, fill or base. Example: cout << setw(10) << x << endl; here setw(10) sets the field width and endl inserts a newline and flushes the stream.
Which one (copy constructor or assignment operator) will be called in each of the following code segment? 1) Matrix m1 (m2); 2) Matrix m1, m2; m1 = m2; 3) Matrix m1 = m2;
1) Matrix m1(m2); - copy constructor (new object created from an existing one). 2) Matrix m1, m2; m1 = m2; - assignment operator (both objects already exist). 3) Matrix m1 = m2; - copy constructor (this is initialisation of a new object, not assignment).
Is it possible to define two functions as given below? Justify your answer. func(int x, int y) func(int &x, int &y)
Not in a useful way. The two declarations have different parameter types (int and int&), so the compiler accepts them, but they cannot be called with variables: for int a, b; the call func(a, b) matches both functions equally well (passing by value and binding a reference are the same rank), so the compiler reports an ambiguous call error. Only a call with literals such as func(2, 3) would compile (it chooses the value version). So these two should not be used as overloaded functions; overloads must differ in a way that lets the call be resolved. (Both also need a return type, e.g. void.)
How can we initialize data members of contained object at construction time?
By using the member initializer list of the containing class's constructor, which passes arguments to the contained object's constructor, e.g. Person(int d, int m, int y) : bday(d, m, y) { }
How the data members of a class are initialized with meaningful values?
By writing a constructor. The constructor is called automatically when an object is created and assigns meaningful initial values to the data members (directly or through an initializer list), e.g. Date() { day = 1; month = 1; year = 2000; }. The default constructor generated by the compiler does not initialize built-in data members.
Can we overload new and delete operators?
Yes. new and delete (and new[]/delete[]) can be overloaded globally or as class member functions to customise memory management, e.g. void* operator new(size_t size); void operator delete(void *p);
What will be the output of following functions if we call these functions three times? 1) void func1(){ int x = 0; x++; cout << x << endl; } 2) void func2(){ static int x = 0 ; x++; cout << x << endl ; }
func1 prints: 1 1 1 (x is an ordinary local variable, re-created and set to 0 on every call) func2 prints: 1 2 3 (static x is initialised only once and keeps its value between calls)
What is the keyword 'this' and what are the uses of 'this' pointer?
'this' is a keyword that, inside a non-static member function, is a pointer holding the address of the object on which the function was called (type X* const for class X). Uses: (1) access the calling object's members, e.g. to separate a member from a parameter with the same name: this->x = x; (2) return the calling object, e.g. return *this; to allow chained calls such as a = b = c or obj.setA(1).setB(2); (3) pass the current object to another function; (4) check self-assignment: if (this != &other).
What is the use of reference data type?
A reference is an alias (another name) for an existing variable, declared as int &ref = x;. It is used mainly for call by reference: a function can modify the caller's variables without pointer syntax, and large objects can be passed (e.g. as const references) without copying. It is also used to return values by reference (e.g. in operator overloading, cout chaining).
What are the main types of operators in terms of number of arguments they take?
Unary operators (one operand, e.g. ++, --, !, unary -), binary operators (two operands, e.g. +, -, *, /, ==) and the single ternary operator ?: (three operands).
What is the this pointer? Give an example of its use
this is a pointer available in every non-static member function that holds the address of the object on which the function is called (type X* const). Example: class Point { int x; public: void setX(int x) { this->x = x; } // this->x is the member, x is the parameter Point& self() { return *this; } };
If the requested memory is not available in the system then what does calloc/malloc and new operator return?
malloc and calloc return a NULL pointer when the requested memory is not available, so the result must be checked. In standard C++ the new operator does not return NULL; it throws a std::bad_alloc exception (very old compilers returned NULL/0, and new (nothrow) returns NULL).
If we want to send the data by reference and don't want that original data should be affected then what can we do to prevent any change?
Pass it as a const reference, e.g. void show(const Student &s);. The data is not copied (efficient), but the compiler gives an error if the function tries to modify it, so the original stays unchanged.
What is returned by new operator?
new returns a pointer (memory address) of the requested type pointing to the newly allocated memory on the heap, e.g. int *p = new int; returns an int*. For new type[n] it returns the address of the first element. If allocation fails, standard C++ throws std::bad_alloc (new (nothrow) returns NULL).
When does an [object] get destroyed?
An object is destroyed (and its destructor called) when its lifetime ends: a local (automatic) object when control leaves the block/function in which it was declared (goes out of scope); a global or static object when the program terminates; a dynamically created object only when delete is applied to its pointer; and a temporary object at the end of the expression that created it.
Identify the errors in the given code and correct them. for ( int i==0; j<numRows; i--) ( for (int j=0;) j<numCols; j--) ( elements [I, j] == m.elements[i][j];
Errors: i==0 is a comparison - initialisation needs i=0; the outer condition tests j instead of i; i-- and j-- should be i++ and j++ (otherwise the loops never end correctly); ( must be { for the loop bodies and the closing braces are missing; the inner for has a stray ) after j=0;; elements[I, j] uses uppercase I and comma indexing - should be elements[i][j]; == is comparison, the copy needs assignment =. Corrected: for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { elements[i][j] = m.elements[i][j]; } }
Following code segment contains errors. Give brief description of each error. Class circle: { Private: double centerX, double center, double radius, Public: setCenter(double.double); setRadius(double); }
Errors: 1. Class must be lowercase class (C++ is case-sensitive). 2. No colon after the class name (circle:) unless inheriting. 3. Private: and Public: must be lowercase private: and public:. 4. Data member declarations must end with semicolons, not commas (double centerX; ...); center should presumably be centerY. 5. Member functions need a return type, e.g. void setCenter(...); void setRadius(double); 6. Parameter types must be separated by a comma: setCenter(double, double), not double.double. 7. The class definition must end with }; (semicolon missing). Corrected: class circle { private: double centerX; double centerY; double radius; public: void setCenter(double, double); void setRadius(double); };
What do you mean by garbage collection and how it works in JAVA and C++ ?
Garbage collection is the automatic freeing of memory that the program no longer uses. Java: objects are created with new and used through references. The Java run-time system tracks objects; when no reference points to an object any more, the garbage collector automatically reclaims its memory, so the programmer never frees memory explicitly. C++: there is no built-in garbage collector. Memory allocated with new (or malloc) must be released by the programmer with delete/delete [] (or free). In classes that allocate dynamic memory, the destructor is written to free it. If the programmer forgets, a memory leak occurs.
Explain the concept of separation of interface from the implementation in the context of classes, using a real world example.
Separation of interface from implementation means users of a class only need to know what it does (its public member functions), not how it does it. The class declaration (public functions) is the interface, usually in a header (.h) file; the bodies of the member functions and private data are the implementation, usually in a .cpp file. The implementation can change without changing code that uses the class, as long as the interface stays the same. Real-world example: a car driver uses the steering wheel, pedals and gear lever (interface) without knowing how the engine or brakes work inside (implementation). A mechanic can replace the engine and the driver still drives the same way. In C++, e.g. class Date { public: void setDate(int, int, int); void print(); private: int d, m, y; }; programs call setDate() and print() only; the internal storage of the date can be changed freely.
Write a simple program using the get() member function of cin object reading a text of 30 characters from the keyboard, store them in an array and then using put() member function of cout object to display them on the screen.
#include <iostream> using namespace std; int main() { char text[31]; int i; cout << "Enter 30 characters: "; for (i = 0; i < 30; i++) cin.get(text[i]); // reads one character, including spaces text[30] = '\0'; cout << "You entered: "; for (i = 0; i < 30; i++) cout.put(text[i]); // writes one character cout.put('\n'); return 0; }
Overload the Binary Assignment (=) Operator. Write a program which has a class List, This class should have Two data members, an array of integers list[] and an integer variable length (i.e. number of elements in the list).The class should further contain a default constructor, a Print() function which display the list and a Function insert() which insert an element in the list and Assignment (= ) Operator function, which contain code for the assignment of one object to other. In main function define two objects list1 and list2 and use the statement list2 = list1; and use (call ) print function with both objects
#include <iostream> using namespace std; const int MAX = 100; class List { private: int list[MAX]; int length; public: List() { length = 0; } void insert(int value) { if (length < MAX) list[length++] = value; else cout << "List is full" << endl; } void Print() { for (int i = 0; i < length; i++) cout << list[i] << " "; cout << endl; } List& operator=(const List& rhs) { if (this != &rhs) { length = rhs.length; for (int i = 0; i < length; i++) list[i] = rhs.list[i]; } return *this; } }; int main() { List list1, list2; list1.insert(10); list1.insert(20); list1.insert(30); list2 = list1; cout << "list1: "; list1.Print(); cout << "list2: "; list2.Print(); return 0; }
Write down the disadvantages of the templates.
1. Code bloat: the compiler generates a separate copy of the function/class for each type used, increasing program size. 2. Compiler error messages for templates are long and hard to understand. 3. Template code is harder to read and write, especially when large and spread over many files. 4. Template definitions usually must be placed in header files, exposing the implementation and increasing compile time. 5. Some older compilers had poor template support, causing portability problems.
Write a program which defines a Template function named Add () which adds two variables and then returns the sum. Define two variables of type int in main function, and then call Add () function on these variables. Program output should look like this: Enter two integer values to be added Enter First value: 12 Enter Second value: 25 Addition of two variable of different data type Sum = 37
#include <iostream> using namespace std; template <class T> T Add(T a, T b) { return a + b; } int main() { int x, y; cout << "Enter two integer values to be added" << endl; cout << "Enter First value:" << endl; cin >> x; cout << "Enter Second value:" << endl; cin >> y; cout << "Addition of two variable of different data type" << endl; cout << "Sum = " << Add(x, y) << endl; return 0; }
In a C++ program, how would you identify whether a declared variable is a "reference variable" or an "address variable"?
Look at the declaration. A reference variable is declared with & after the type and must be initialized with an existing variable, e.g. int &ref = x; it is an alias, used without any dereference operator, and cannot be re-seated or be null. An address (pointer) variable is declared with *, e.g. int *ptr = &x; it stores an address, is accessed with *ptr (dereference), can be NULL and can be made to point elsewhere. Note: & in a declaration means reference, while & in an expression (e.g. &x) means address-of.
What will be the output of given program code ? class File { private: char *name; char *type; int size; public: File() { File::num_files++; } static int num_files; }; int File::num_files = 0; main() { File f1; cout<<f1.num_files<<endl; File f2; cout<<f2.num_files<<endl; cout<<File::num_files; return 0; }
Output: 1 2 2 num_files is a public static member shared by all objects; each constructor call increments it, so after f1 it is 1 and after f2 it is 2, whether accessed through f1, f2 or the class name.
Write a program that defines a Template function named Square() which finds the square of a number and then return it. Define one variable of type float in main function and then call Square function on that. Program output should look like this: Enter a float value to find its Square: 12.3 Square of float number is: 151.29
#include <iostream> using namespace std; template <class T> T Square(T num) { return num * num; } int main() { float value; cout << "Enter a float value to find its Square: "; cin >> value; cout << "Square of float number is: " << Square(value) << endl; return 0; }
Let suppose class String{ private: char *str; public: void operator = (const String &s){ delete str; str = new char[strlen(s.str)+1]; strcpy(str, s.str); } }; main(){ String s, *sptr; sptr=&s; ....... s = *sptr ....... } Bad coding practice has been adopted here, identify and describe it in words. Also write correct code for assignment operator.
Problem: s = *sptr assigns the object to itself (self-assignment). The operator first deletes str, which is also s.str, and then calls strlen(s.str) and strcpy from memory that was already freed, so the result is undefined (garbage or crash). Also delete should be delete[] because the memory came from new[], and returning void prevents chained assignment (a = b = c). Correct operator: String& operator=(const String &s) { if (this != &s) // guard against self-assignment { delete [] str; str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } return *this; }
Write a small program which defines a user-defined manipulator named Octal. This manipulator should convert and display the decimal number into octal form. In the main function, You have to take a decimal number as an input from the user and then by using the user-defined manipulator display the number in octal form.
#include <iostream> using namespace std; ostream& Octal(ostream &os) { os << oct; // switch the stream to octal return os; } int main() { int num; cout << "Enter a decimal number: "; cin >> num; cout << "Octal form: " << Octal << num << dec << endl; return 0; }
Write a program that defines a Template function named Square() which finds the square of a number and then return it. Define one variable of type double in main function and then call Square function on that. Program output should look like this: Enter a double value to find its Square: 235.3 Square of double number is: 55366.1
#include <iostream> using namespace std; template <class T> T Square(T num) { return num * num; } int main() { double d; cout << "Enter a double value to find its Square: "; cin >> d; cout << "Square of double number is: " << Square(d) << endl; return 0; }
Given is the code for the class myClass. class myClass { private: int x; int y; public: myClass() { x = 0; y = 0; } }; You are required to write the code to perform the following task in the main() function. - Prompt the user to enter the number of objects to be created. - Dynamically allocate memory to objects according to the size entered by user. - De-allocate memory that was allocated to objects.
int main() { int n; cout << "Enter the number of objects to be created: "; cin >> n; myClass *ptr = new myClass[n]; // default constructor runs for each object // ... use the objects ... delete [] ptr; // free the whole array ptr = NULL; return 0; }
Write a small program which defines a user define manipulator named star, this manipulator should display the output separated by four stars. For example the output of the program should look like this Virtual****University
#include <iostream> using namespace std; ostream & star(ostream &os) { os << "****"; return os; } int main() { cout << "Virtual" << star << "University" << endl; return 0; }
Find the errors in given code segment and also correct them. class Data { private: const int data; public: Data() { cout<<"Constructor Called...\n"; } void getIncreament() { cout<<"Data = " << ++ data; } }; void main() { char * String ; String = New char[15]; String = "Welcome To VU"; cout<<String; free (String); }
Errors: 1. const int data is never initialized; a const member must be initialized in the constructor's member initializer list. 2. ++data tries to modify a const member (not allowed). Print data + 1 instead, or make data non-const. 3. New must be written in lowercase: new. 4. String = "Welcome To VU"; makes the pointer point to a string literal, losing (leaking) the memory from new; copy the text with strcpy instead. 5. Memory allocated with new[] must be released with delete[], not free(). 6. main should return int. Corrected code: #include <iostream> #include <cstring> using namespace std; class Data { private: const int data; public: Data() : data(0) { cout << "Constructor Called...\n"; } void getIncreament() { cout << "Data = " << data + 1; } }; int main() { char *String; String = new char[15]; strcpy(String, "Welcome To VU"); cout << String; delete[] String; return 0; }
Write a program which defines three variables of type double which store three different values including decimal points, using setprecision manipulators to print all these values with different numbers of digits after the decimal point.
#include <iostream> #include <iomanip> using namespace std; int main() { double x1 = 12345624.72345; double x2 = 987654.12345; double x3 = 1985.23456; cout << fixed; // precision now means digits after the decimal point cout << setprecision(1) << x1 << endl; // 12345624.7 cout << setprecision(3) << x2 << endl; // 987654.123 cout << setprecision(5) << x3 << endl; // 1985.23456 return 0; }
Define buffer? Explain its usage?
A buffer is a temporary area of memory where data is collected while being moved between a program and a device (disk, screen, keyboard). Usage: instead of writing or reading every byte separately, the stream gathers data in the buffer and transfers the whole block in one operation (e.g. when the buffer is full, on endl/flush, or when the file is closed). Because disk and device operations are slow, buffering reduces the number of I/O operations and makes the program much faster. For input, the keyboard buffer holds typed characters until Enter is pressed and then cin reads from it.
What are the advantages and disadvantages of using templates?
Advantages: - Write one generic version of a function or class instead of a separate copy for every data type, so less code to write and maintain. - Type-safe: types are known at compile time so the compiler checks them. - Generic code is reusable (e.g. the STL containers) and fast, as no run-time overhead is added. Disadvantages: - Templates can make code hard to read and debug. - Compiler error messages for templates are long and confusing. - Definitions usually have to be placed in header files, increasing compile time and exposing the implementation. - Separate code is generated for each type used, which can increase program size (code bloat). - Syntax problems such as the angle-bracket (>>) problem in old compilers.
Suppose a program has a math class having only one data member number. Write the declaration and definition of operator function to overload + operator for the statements of main function. math obj1, obj2; obj2= 10 + obj1 ;
Because the left operand (10) is an int, not a math object, the operator must be a non-member (friend) function taking int and math: class math { int number; public: math(int n = 0) { number = n; } friend math operator+(int value, const math &m); // declaration }; math operator+(int value, const math &m) // definition { math temp; temp.number = value + m.number; return temp; }
What is the difference between function overloading and operator overloading?
Function overloading: several functions with the same name but different parameter lists (different number, type or order of parameters) are defined; the compiler chooses which one to call from the arguments, e.g. int max(int,int) and double max(double,double). Operator overloading: an existing C++ operator (+, -, ==, <<, etc.) is given a new meaning for user-defined types by writing a special function named operator followed by the symbol, e.g. Complex operator+(Complex). The operator's precedence, associativity and number of operands cannot be changed and new operator symbols cannot be created. In fact operator overloading is a special form of function overloading where the function name is operatorX and it is called by using the operator in an expression.
Why the first parameter of operator function for << operator must be passed by reference?
The first parameter of operator<< is the output stream (ostream &os). It must be a reference because: (1) stream objects cannot be copied - the copy constructor of ostream is not accessible, so passing by value does not compile; (2) the function must write to the original stream (e.g. cout or a file stream), not a copy, so that the output really appears there and the stream's state changes are kept; (3) the function returns this same stream by reference (return os;) so that calls can be chained, e.g. cout << obj1 << obj2. Example: friend ostream& operator<<(ostream &os, const Date &d);
Write the general syntax of a class that has one function as a friend of a class along with definition of friend function.
class ClassName { private: int a, b; public: ClassName(int x, int y) { a = x; b = y; } friend int compute(ClassName obj); // friend declaration }; // definition: not a member, so no ClassName:: and no friend keyword int compute(ClassName obj) { return obj.a + obj.b; // may access private members }
Write a program which consists of two classes, Date and Person. Date class should contain three data members day, month, year and setter and getter function for these data members. Date class should also contain showdate() member function to display date. Person class should contain three data members Name, Address, and Bday, where Name and Address are char pointer while Bday (Date of birth) is of type Date, Person class should further contain two member functions Display() and setdate(). In main program Create an object of Class person and call the member functions with it.
#include <iostream> #include <cstring> using namespace std; class Date { private: int day, month, year; public: Date() { day = 1; month = 1; year = 2000; } void setDay(int d) { day = d; } void setMonth(int m) { month = m; } void setYear(int y) { year = y; } int getDay() { return day; } int getMonth() { return month; } int getYear() { return year; } void showDate() { cout << day << "-" << month << "-" << year << endl; } }; class Person { private: char *Name; char *Address; Date Bday; public: Person(const char *n, const char *a) { Name = new char[strlen(n) + 1]; strcpy(Name, n); Address = new char[strlen(a) + 1]; strcpy(Address, a); } ~Person() { delete [] Name; delete [] Address; } void setdate(int d, int m, int y) { Bday.setDay(d); Bday.setMonth(m); Bday.setYear(y); } void Display() { cout << "Name: " << Name << endl; cout << "Address: " << Address << endl; cout << "Date of Birth: "; Bday.showDate(); } }; int main() { Person p("Ali", "Lahore"); p.setdate(15, 8, 1995); p.Display(); return 0; }
Write a C++ program that contains a class 'myClass' having two data members of type int. The class must have - A default constructor which must initialize all the data members to their meaningful values. - A destructor with no implementation. - Setter member functions to set all data members of class - Getter member functions to get all data members of class In main function of the program 5. Prompt the user to enter the number of objects to be created. 6. Dynamically allocate memory to objects according to the size entered by user. 7. De-allocate memory that was allocated to objects
#include <iostream> using namespace std; class myClass { private: int a; int b; public: myClass() { a = 0; b = 0; } // default constructor ~myClass() { } // destructor with no implementation void setA(int x) { a = x; } void setB(int y) { b = y; } int getA() { return a; } int getB() { return b; } }; int main() { int num; cout << "Enter the number of objects to be created: "; cin >> num; if (num <= 0) return 0; myClass *objects = new myClass[num]; // dynamic allocation; default constructor runs for each for (int i = 0; i < num; i++) { objects[i].setA(i + 1); objects[i].setB((i + 1) * 10); cout << "Object " << i + 1 << ": a = " << objects[i].getA() << ", b = " << objects[i].getB() << endl; } delete [] objects; // de-allocation; destructor runs for each return 0; }
Write a program which defines two variables var1 and var2 of type int and stores two different values in these variables. Print the values of these variables in three different number systems using manipulators dec, hex, oct.
#include <iostream> using namespace std; int main() { int var1 = 100, var2 = 255; cout << "Decimal: " << dec << var1 << " " << var2 << endl; // 100 255 cout << "Hexadecimal: " << hex << var1 << " " << var2 << endl; // 64 ff cout << "Octal: " << oct << var1 << " " << var2 << endl; // 144 377 cout << dec; // restore decimal base return 0; }
Write a function to overload subtraction operator for Class Order, which you created in previous question. The class has following attributes/ data members i) OrderID ii) Items iii) PricesOfItems Write the main () to call the - operator and print the result also. This operator should subtract the items of one object from the other.
#include <iostream> using namespace std; const int MAX = 100; class Order { int OrderID; int Items; double PricesOfItems[MAX]; public: Order(int id = 1, int items = 1) { OrderID = id; Items = items; for (int i = 0; i < MAX; i++) PricesOfItems[i] = 0; } int getOrderID() { return OrderID; } int getItems() { return Items; } // subtract the items of the right object from the left object Order operator-(const Order &other) const { Order result(OrderID, Items - other.Items); if (result.Items < 0) result.Items = 0; for (int i = 0; i < result.Items; i++) result.PricesOfItems[i] = PricesOfItems[i]; return result; } }; int main() { Order o1(101, 10), o2(102, 4); Order o3 = o1 - o2; cout << "Order " << o3.getOrderID() << " items after subtraction: " << o3.getItems() << endl; // prints 6 return 0; }
Briefly describe the role of each of the following within a class: 1. Instance variables 2. Instance methods 3. Constructors
1. Instance variables (data members) hold the state of an object; every object of the class gets its own copy, usually kept private. 2. Instance methods (member functions) define the behaviour of the object; they operate on that object's data members and provide the public interface (for example getters and setters). 3. Constructors are special member functions with the same name as the class and no return type; they are called automatically when an object is created to initialize its data members (they can be overloaded and take default arguments).
Create a class named Order. This class has the following attributes/ data members i) OrderID ii) Items iii) PricesOfItems a) Create the object of this class using parameterized constructor in order to initialize OrderID and Items data members. Default values of both the data members must be equal to 1. b) Write the following member functions of this class; i) OrderBill ( ), this function will calculate the invoice of an order and display the result. The formula to calculate the invoice is invoice=SumPrices(); ii) SumPrices( ), this function will sum the prices of the items entered by the user from keyboard in PricesOfItems array and returns the result. c) Write the setter functions for OrderID, Items, and PricesOfItems. And getter functions for OrderID and Items. Also write the main () to create the object of class Order.
#include <iostream> using namespace std; const int MAX = 100; class Order { int OrderID; int Items; double PricesOfItems[MAX]; public: // a) parameterized constructor with default values 1 Order(int id = 1, int items = 1) { OrderID = id; setItems(items); for (int i = 0; i < MAX; i++) PricesOfItems[i] = 0; } // c) setters void setOrderID(int id) { OrderID = id; } void setItems(int n) { if (n < 1) n = 1; if (n > MAX) n = MAX; Items = n; } void setPricesOfItems() { // prices entered from keyboard for (int i = 0; i < Items; i++) { cout << "Enter price of item " << i + 1 << ": "; cin >> PricesOfItems[i]; } } // c) getters int getOrderID() { return OrderID; } int getItems() { return Items; } // b-ii) sum of prices double SumPrices() { double sum = 0; for (int i = 0; i < Items; i++) sum += PricesOfItems[i]; return sum; } // b-i) invoice void OrderBill() { double invoice = SumPrices(); cout << "Order ID: " << OrderID << ", Items: " << Items << ", Invoice: " << invoice << endl; } }; int main() { Order order(10, 3); // OrderID = 10, Items = 3 order.setPricesOfItems(); order.OrderBill(); Order def; // uses default values 1, 1 cout << def.getOrderID() << " " << def.getItems() << endl; return 0; }
What is a friend function? Explain with example?
A friend function is a non-member function that a class declares with the keyword friend inside its body. It is not called through an object (no this pointer), but it is allowed to access the private and protected members of that class. Friendship is granted by the class, it is not inherited and not mutual. #include <iostream> using namespace std; class Box { int width; // private public: Box(int w) { width = w; } friend void showWidth(Box b); // friend declaration }; void showWidth(Box b) { // ordinary function, not a member cout << "Width: " << b.width << endl; // can read private data } int main() { Box b(5); showWidth(b); // called like a normal function return 0; }
Write a program that uses a function template called min to determine the smaller of two arguments. Test the program using integer, character and floating point number pairs in main ().
#include <iostream> using namespace std; template <class T> T min(T a, T b) { return (a < b) ? a : b; } int main() { cout << "min(10, 4) = " << ::min(10, 4) << endl; cout << "min('x', 'c') = " << ::min('x', 'c') << endl; cout << "min(2.5, 7.25) = " << ::min(2.5, 7.25) << endl; return 0; }
Create a class named Account, its data members are i. Account NO ii. Account Title iii. Balance a) Create the object of this class using parameterized constructor in order to initialize all the three data members i.e. Account NO. Account Title. Balance b) Write a member function of this class named deposit (), this function will calculate the current balance for the user's account. In deposit function user will be prompted to enter the amount to be deposited and displays the incremented balance. c) Write an other member function of this class named addToFile(), In this function write the values of the data members Account NO, Account Title and Balance in the file named Account.txt. Also write the getter and setter functions for the data members of this class
#include <iostream> #include <fstream> #include <cstring> using namespace std; class Account { int accountNo; char accountTitle[50]; double balance; public: // a) parameterized constructor Account(int no, const char *title, double bal) { accountNo = no; setAccountTitle(title); balance = bal; } // setters void setAccountNo(int no) { accountNo = no; } void setAccountTitle(const char *title) { strncpy(accountTitle, title, 49); accountTitle[49] = '\0'; } void setBalance(double bal) { balance = bal; } // getters int getAccountNo() { return accountNo; } const char *getAccountTitle() { return accountTitle; } double getBalance() { return balance; } // b) deposit void deposit() { double amount; cout << "Enter amount to deposit: "; cin >> amount; if (amount > 0) balance += amount; else cout << "Invalid amount" << endl; cout << "Current balance: " << balance << endl; } // c) write data members to Account.txt void addToFile() { ofstream out("Account.txt", ios::app); if (!out) { cout << "Cannot open file" << endl; return; } out << accountNo << " " << accountTitle << " " << balance << endl; out.close(); } }; int main() { Account acc(1001, "Ali Khan", 5000); acc.deposit(); acc.addToFile(); return 0; }
Write a class Rectangle that performs the mathematical operations (Subtraction and Multiplication) on its height and width with the help of operator overloading. Class Rectangle should have the following Private data members 1. height 2. width a) Write a parameterized constructor to initialize the data members. b) Write member functions to Overload the following Operators and Display the Results. 1. - 2. * Implement the following checks in operator overloading functions: i. Check for negative values in subtraction before and after the operation, change them into absolute values or negate them. (If width = -3 its absolute value is width=3.) ii. Check for zero values in multiplication. If any value is zero, displays a message" Height or width cannot be zero". And exit from the function. In main () create the objects of the class and assign values to their data members and then call the overloaded operators
#include <iostream> using namespace std; class Rectangle { int height; int width; static int absVal(int v) { return v < 0 ? -v : v; } public: Rectangle(int h = 0, int w = 0) { height = h; width = w; } void display() { cout << "Height = " << height << ", Width = " << width << endl; } Rectangle operator-(const Rectangle &r) { // check before the operation int h1 = absVal(height), w1 = absVal(width); int h2 = absVal(r.height), w2 = absVal(r.width); Rectangle result(h1 - h2, w1 - w2); // check after the operation result.height = absVal(result.height); result.width = absVal(result.width); cout << "Subtraction: "; result.display(); return result; } Rectangle operator*(const Rectangle &r) { if (height == 0 || width == 0 || r.height == 0 || r.width == 0) { cout << "Height or width cannot be zero" << endl; return *this; // exit from the function } Rectangle result(height * r.height, width * r.width); cout << "Multiplication: "; result.display(); return result; } }; int main() { Rectangle r1(5, -3), r2(8, 2), r3(0, 4); Rectangle a = r1 - r2; // Height = 3, Width = 1 Rectangle b = r1 * r2; // Height = 40, Width = -6 Rectangle c = r1 * r3; // prints the zero message return 0; }