Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this possible to use in c++?

  1. To my surprise, I found that the name of a c++ object can be the same as class name. Can someone explain to me the reason why?
  2. When I declare an object of class a as a a1(), it does not raise an error, but doesn't call the constructor. Why is this happening?

My code:

#include<iostream>
using namespace std;

class a 
{
    public:
    a() 
    {
        cout << "in a\n";
    }
};

int main()
{
    a a1();
    a a;
}
like image 862
nihar Avatar asked Oct 08 '13 14:10

nihar


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

What is this in C language?

In C, this is a normal parameter name, no different from any other name. You're probably using a C++ compiler, where this is a keyword and will give an error when used as a parameter.

What does -= mean in C++?

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A.

Can I use Auto in C?

C language uses 4 storage classes, namely: auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language.


1 Answers

When you write a a1(); it is actually being parsed as a function declaration not a call to the default constructor.

a a1;

will call the default constructor correctly

When you write a a; it works because the variable name takes preference over the class name in what is called name hiding, but even though it works it will only lead to confusion and I would avoid doing it.

And for all those people who like standards quotes here you go

A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

like image 158
aaronman Avatar answered Sep 20 '22 23:09

aaronman