© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

6. How can method defined in multiple base classes with same name can be invoked from derived class simultaneously ?

Ans:

Ex:

class x
{
public:
m1();

};

class y
{
public:
m1();

};

class z :public x, public y
{
public:
m1()
{
x::m1();
y::m1();
}

};

 

Ex Q1: Find the output of the following program

class Sample
{
public:
        int *ptr;
        Sample(int i)
        {
        ptr = new int(i);
        }
        ~Sample()
        {
        delete ptr;
        }
        void PrintVal()
        {
        cout << "The value is " << *ptr;
        }
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}

Ans:
Say i am in someFunc
Null pointer assignment(Run-time error)

Explanation:

As the object is passed by value to SomeFunc  the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr  that has been freed.The solution is to pass the Sample object  by reference to SomeFunc:
 
void SomeFunc(Sample &x)
{
cout << "Say i am in someFunc " << endl;
}
because when we pass objects by refernece that object is not destroyed. while returning from the function.

SLogix Student Projects
bottom