Shreyan Mehta
Shreyan Mehta

Reputation: 550

why constructors need scope resolution to define it outside the body?

if we declare a member function of a class inside the class and write its definition outside of class , then it is understood that we need to use scope resolution operator since there might be n number of functions of same name in other class...

//assume required header libraries included
class temp{
int x;
public:
void outp();
};
class qwerty{
int x;
public:
void outp()
{ std::cout<<x;}
};
void temp::outp()
{ std::cout<<x; }

but since class name is always unique... so constructor name would also be unique so why we still need to use scope resolution in defining constructor outside the class body

class temp{
int x;
temp();
};
temp::temp(){
x=0;
}

and not directly

temp(){
x=0;
}

or perhaps

::temp(){
x=0
};

like i know in c++ we need to use scope resolution for things out of scope...so why not the above code...?

Upvotes: 0

Views: 2417

Answers (1)

Yam Marcovic
Yam Marcovic

Reputation: 8141

In the early days of C, you didn't have to explicitly specify a return type for a function. If you didn't, it was assumed to be int. When C++ evolved, it needed to be backwards compatible with C, and there were already many C programs which relied on this behavior to some extent. For many years, even though not specifying a return type had become an error both in C and in C++, compilers still only generated warnings for it, probably to avoid breaking existing code.

Hence, at that time, writing something like

MyClass() { /* ... */ }

might have been interpreted as a function int MyClass(void). And if you wrote a class, you didn't want to conflict with that function.

Also, since the constructor is a function, after all, it makes sense to treat all member function definitions consistently.

Upvotes: 4

Related Questions