Question 14: Predict the output.
class
{
public:
void display()
{
std::cout<<"Display function without any class name";
}
}classWithoutAnyName;
int main()
{
classWithoutAnyName.display();
}
Options:
(a) Display function without any class name.
(b) Runtime Error
(c) Compile Time error: Class doesn’t have any name.
(d) None of the above.
Answer: a
We can have a class without a name in C++ .
ReplyDeleteObject Creation :
Objects of such a class can be created along with the class definition as shown above .
Passing Arguments to Function :
Cant be done . Although we can always pass a void* . But the class won't know how to handle it .
Constructors and Destructors :
Such a class cant have any .
Quoting "Passing Arguments to Function :
DeleteCant be done . Although we can always pass a void* . But the class won't know how to handle it"
Can you please explain? If you are allowed to pass a void*, then you can definitely know how to handle it... isn't it?
Hi Kaush.rasto,
DeleteIt is allowed to pass an argument to a function, as object is created so this pointer exists for the object created.
For example:
Following code is valid too.....
class
{
public:
void setValue(int value)
{
m_data = value;
}
void display()
{
std::cout<<"Display function without any class name"<<"\n Value is : "<<m_data;
}
private:
int m_data;
}classWithoutAnyName;
int main()
{
classWithoutAnyName.setValue(20);
classWithoutAnyName.display();
}