I'm studing C++ and I can't understand the meaning of the boldface sentence below:
From IBM manual:
The following restrictions apply to constructors and destructors:
- Constructors and destructors do not have return types nor can they return values.
- References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
- Constructors cannot be declared with the keyword virtual.
- Constructors and destructors cannot be declared static, const, or volatile.
- Unions cannot contain class objects that have constructors or destructors.
Could you please provide me an example? Thank you!
Limitations on Constructors:-A constructor function does not have any return type, not even void. Hence, constructor functions can't return any value. A constructor function may not be static. We cannot fetch the address of a constructor function.
Rules to be rememberedA constructor does not have return type. The name of the constructor is same as the name of the class. A constructor cannot be abstract, final, static and Synchronized. You can use the access specifiers public, protected & private with constructors.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
The sentence means that you can't take pointer to a constructor or a destructor. Here's an example:
class Sample{
private: int x;
public: Sample() { x = 100; };
public: void* member() { x = 200; };
};
template <class X>
void call_me(Sample s, X function){
(s.*function)();
};
call_me(s, &Sample::member); //valid
call_me(s, &Sample::Sample); //invalid
call_me(s, &Sample::~Sample); //invalid
The rationale is like this:
s.member()
).You cannot make a function pointer (or reference) that points to a constructor.
The first guess would be that you can't create a reference or a pointer to a constructor/destructor. Of course, "a reference or a pointer" in this case (if they were possible) would have reference-to-member or pointer-to-member type, since these member functions are not static. However, this interpretation is a problematic for one reason: in C++ there's no such thing as a reference-to-member.
Basically, the mention of "reference" within this interpretation does not make any sense: you can't have a reference to any non-static member function of a class, regardless of whether it is a constructor/destructor or not. There's simply no such thing in C++.
If the above interpretation is correct (as other answers also suggested), the more meaningful (yet still not prefect) wording would be
The mention of "references" in this context makes no sense whatsoever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With