#include<iostream>
using
namespace
std;
class
Base1 {
public
:
Base1()
{ cout <<
" Base1's constructor called"
<< endl; }
};
class
Base2 {
public
:
Base2()
{ cout <<
"Base2's constructor called"
<< endl; }
};
class
Derived:
public
Base1,
public
Base2 {
public
:
Derived()
{ cout <<
"Derived's constructor called"
<< endl; }
};
int
main()
{
Derived d;
return
0;
}
OPTIONS:
(A) Compiler Dependent
(B) Base1′s constructor called
Base2′s constructor called
Derived’s constructor called
(C) Base2′s constructor called
Base1′s constructor called
Derived’s constructor called
(D) Compiler Error
ANSWER:
Answer: (B)
Explanation: When a class inherits from multiple classes, constructors of base classes are called in the same order as they are specified in inheritance.
#include<iostream>
using namespace std;
class Base
{
public :
void show()
{
cout<< " In Base " ;
}
};
class Derived: public Base
{
public :
int x;
void show()
{
cout<< "In Derived " ;
}
Derived()
{
x = 10;
}
};
int main( void )
{
Base *bp, b;
Derived d;
bp = &d;
bp->show();
cout << bp->x;
return 0;
}
OPTIONS:
(A) Compiler Error in line ” bp->show()”
(B) Compiler Error in line ” cout << bp->x”
(C) In Base 10
(D) In Derived 10
Answer: (B)
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer.
#include<iostream>
using namespace std;
class Base1
{
public :
char c;
};
class Base2
{
public :
int c;
};
class Derived: public Base1, public Base2
{
public :
void show() { cout << c; }
};
int main( void )
{
Derived d;
d.show();
return 0;
}
OPTIONS:
(A) Compiler Error in “cout << c;" (B) Garbage Value
(C) Compiler Error in “class Derived: public Base1, public Base2″
Answer: (A)
Explanation: The variable ‘c’ is present in both super classes of Derived. So the access to ‘c’ is ambiguous. The ambiguity can be removed by using scope resolution operator.
#include<iostream>
using namespace std;
class Base1
{
public :
char c;
};
class Base2
{
public :
int c;
};
class Derived: public Base1, public Base2
{
public :
void show() { cout << Base2::c; }
};
int main( void )
{
Derived d;
d.show();
return 0;
}
|
|
|
No comments:
Post a Comment