Can we do something like this:
#include <iostream>
class Foo
{
public:
Foo() { std::cout << sizeof(*this) << '\n'; }
};
In C Standard i see the following:
ISO/IEC 9899:2011
6.7.2.1 Structure and union specifiers
8 ... The type is incomplete until immediately after the } that terminates the list, and complete thereafter.
But in C++ Standard i can't find any analogue.
The sizeof operator shall not be applied to an expression that has incomplete type, so can we write such code or not?
Yes, you can write such code because the compiler has to treat it as though the class definition is complete inside class method implementations.
For example it has to treat it as though you wrote:
#include <iostream>
class Foo
{
public:
Foo();
};
// Methods declared in the body of a class are implicitly inline
// Inline, however, probably doesn't mean what you think it means:
inline Foo::Foo() { std::cout << sizeof(*this) << '\n'; }
Inside the member function body, the class is complete- else, you could not access any other member functions, nor access any member variables, which would make a fairly worthless member.
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