This section contains Aptitude Questions and Answers on class, object and related topics in C++ programming language.
1) Which type of Access Specifier class data member number is?
//a simple class
class test_example
{
int number;
};
- private
- public
- protected
- default
Correct Answer - 1
private
By default, class data members and member functions are private.
2) What will be the output of this program?
#include <iostream>
using namespace std;
class sample
{
int x;
}
int main()
{
sample obj;
obj.x=100;
cout<<"x="<<obj.x<<endl;
}
- x=10
- Error
Correct Answer - 2
Error: Can’t access private members outside of the class
By default, class data members and member functions are private, and we cannot access private members outside of the class.
3) Which variable(s) is/are accessible in main() function?
class sample
{
private:
int x;
protected:
int y;
public:
int z;
}
- x
- y
- z
- y and z
Correct Answer - 3
z
Only variable z is accessible outside of the class and we can access it in main().
4) Write statement to print value of var ?
int var=100;
class sample
{
private:
void showVal(void)
{
...
}
}
- cout<<var;
- cout<<::var;
- Cannot access var inside class member function.
- Both 1 and 2
Correct Answer - 4
cout<<x; and cout<<::x;
var is global variable and there is no other variable with same name in class definition, so we can access value of var using both statements.
5) Where a protected member can be accessed?
- Within the same class
- Outside of the class
- Within the Derived class
- Both 1 and 3
Correct Answer - 4
Both 1 and 3
Protected Members access within the same class and derived classes.
6) A C+++ class contains...
- Member Functions
- Data Members
- Both 1 and 2
- Customize main () function
Correct Answer - 3
Both 1 and 2
A class definition contains both data members and member functions.
7) Where a class member function can be defined?
- Inside the class definition
- Outside of the class definition
- Both 1 and 2
- Don’t know
Correct Answer - 3
Both 1 and 2
A class member function can be defined inside the class definition as well as outside of the class definition.
8) Can we declare a member function private?
- Yes
- No
Correct Answer - 1
Yes
Yes, a member function can be declared as private.
9) What will be the output of this program?
#include <iostream>
using namespace std;
//Empty class
class test
{
};
int main()
{
test testObj;
cout<<"size ="<<sizeof(testObj);
return 0;
}
- Error
- size =Garbage
- size =1
Correct Answer - 3
size =1
An empty class object takes 1 byte in the memory, but it is not fixed it can be take any non zero value depending on the compiler and class definition.