Why does the following c++11/14 code not work? Here I am forward declaring an enum within the class. Objective is not to have a huge - 100s of values of enums within the class - which makes the class unreadable. I cannot use a separate scoped enum for this - for political reasons.
class A {
public:
// forward declare the enum
enum B : int;
void func (B b) {}
};
// The actual declaration
enum A::B : int {
Val1,
Val2,
};
int main ()
{
// B is unscoped. so I should be able to use it as below?
int a = A::Val1;
}
Compilation Error
tmp.cpp: In function ‘int main()’:
tmp.cpp:13:5: error: ‘A::B Val1’ is private
Val1,
^
tmp.cpp:19:16: error: within this context
int a = A::Val1;
^
But the following code works :
int a = A::B::Val1;
That error appears in G++ but not in Visual C++ and clang. Formally enum's id can be used as namespace, or can be skipped, but last two do skip it by default, while latest g++ enforces it. That's changeable by compiler options. Use of enum class' id is mandatory:
class A {
public:
// forward declare the enum
enum class B : int;
void func (B b) {}
};
// The actual declaration
enum class A::B : int {
Val1,
Val2,
};
int main ()
{
int a = static_cast<int>(A::B::Val1); // no implicit cast
}
Related
I have always tried to avoid friend concept because it beats the purpose of encapsulation. However, I was just experimenting with the concept and the following code fails to compile with the following error:
main.cpp:29:28: error: ‘int A::a’ is private within this context
On the other hand, if I just place the class B before class A with forward declaration of class A, it runs fine. Am I missing something really trivial here?
#include <iostream>
class A {
int a;
public:
A() { a = 0; }
// friend function
friend void B::showA(A& x);
};
class B
{
public:
void showA(A&);
private:
int b;
};
void B::showA(A& x)
{
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
As it is, you are using class B within class A, but as you can see B is not declared before it is used.
That is causing an error like this:
error: 'B' has not been declared
and a little further
error: int 'A::a' is private within this context
because the friendship relationship has not been linked due to the first error (as A::a is by default private)
You may try then to forward-declare B, like the following
#include<..>
class B;
class A {
int a;
public:
A() { a = 0; }
// friend function
friend void B::showA(A& x);
};
class B{
...
}
...
This would generate an error error: invalid use of incomplete type 'class B' because a forward declaration only says that a particular
class (here class B) will be defined later so you can reference it or have pointers to it, but it does not say what members this class
will have, so the compiler is unable to know if your future class Bwould have a B::showA method, thus the error, incomplete type error. At this time, the compiler does not know if your future class B (used in class A) would have a function B::showA.
The simplest solution would be to declare B before A and then forward declare A (with class A;) as follows. This way, you tell the compiler - here is my class B declaration (it contains a method B::showA),
and it uses a class A that I will define later. As there is no need to known what would be the content of A, it will compile.
// as you use class A before it is declared, you need to forward declare it
class A;
class B
{
public:
void showA(A&);
private:
int b;
};
class A {
int a;
...
This would compile and execute the function B::showA.
I'm trying to understand how the compiler handles this code. The two class methods both reference the enumeration before it is defined, but only one generates a compile error. I'm using GCC 9.2:
class Test {
public:
Test() {}
~Test(){}
//gcc seems to be happy with this...
int Foo()
{
TestState v = TestState::Value1;
if (v == TestState::Value1) {
return 0;
} else if (v == TestState::Value2) {
return 1;
}
}
// ... but it doesn't work when used as a parameter
int Bar(TestState v)
{
if (v == TestState::Value1) {
return 0;
} else if (v == TestState::Value2) {
return 1;
}
}
private:
enum class TestState:bool
{
Value1 = false,
Value2 = true
};
};
In this case, the function Foo compiles fine under gcc 9.2, but Bar does not:
enum.cpp:18:13: error: ‘TestState’ has not been declared
int Bar(TestState v)
^
enum.cpp: In member function ‘int Test::Bar(int)’:
enum.cpp:20:13: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
if (v == TestState::Value1) {
^
enum.cpp:22:20: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
} else if (v == TestState::Value2) {
Why does gcc seem to accept the usage of the enum prior to definition in one instance but not another? I understand that the enum should be declared before these functions, but why does Foo compile without error?
Maybe you can see this as a lack of declaration of TestState by the time Bar(TestState) is declared. Actually this code can be simplified as below:
struct A {
void f() {} /// fine
void g(B) {} /// not fine
struct B {};
};
int main() {
return 0;
}
This code just can't compile as yours, since by the time g(B) is declared, the compiler needs to look up where the declaration of B is, which cannot be found.
That's when we need Forward Declaration. Add a forward declaration, and you may find compilation successful:
struct A {
void f() {} /// fine
struct B;
void g(B) {} /// fine now
struct B {};
};
int main() {
return 0;
}
It's the same with your code. So add private: enum class TestState : bool; before the public in your code, and it'll compile.
Scenario 1: No compilation issue.When base class is initialized in derived class using initialization list
class Base
{
public:
int x;
};
class D:public Base
{
public:
int y;
D(int y1):Base{y1+1},y{y1}{}
};
int main()
{
D d(5);
return 0;
}
Scenario 2: Not compiling and asking for parameterized constructor . Note virtual destructor in base class
$g++ -o main *.cpp
main.cpp: In constructor ‘D::D(int)’:
main.cpp:16:34: error: no matching function for call to ‘Base::Base()’
D(int y1):Base{y1+1},y{y1}{}
^
main.cpp:5:7: note: candidate: Base::Base()
class Base
^~~~
main.cpp:5:7: note: candidate expects 0 arguments, 1 provided
main.cpp:5:7: note: candidate: constexpr Base::Base(const Base&)
main.cpp:5:7: note: no known conversion for argument 1 from ‘int’ to ‘const Base&’
class Base
{
public:
int x;
virtual ~Base(){}
};
class D:public Base
{
public:
int y;
D(int y1):Base{y1+1},y{y1}{}
};
int main()
{
D d(5);
return 0;
}
Base{y1+1} is an aggregate initialization. It only works on aggregates. In your second snippet, since Base contains a virtual function, it is no longer an aggregate, and so you can't initialize it like that.
class Foo
{
public:
Foo(int& cnt) : cnt_(cnt) {}
void test() const
{
cnt_ = 0;
}
protected:
int& cnt_;
};
int cnt;
int main()
{
Foo foo(cnt);
foo.test();
}
The above code compiles. The test function is const, however we are allowed
to change the value of cnt_. If "cnt_" is not a reference then compiler
gives an error as expected. However if "cnt_" is a reference like above,
why doesn't compiler give an error ? We are still changing the state of the
object "Foo" inside a const member function, isn't it ?
The member cnt_, declared as:
int& cnt_;
is a reference, and inside the member function:
void test() const;
the const-qualification is applied to the members, i.e.: the reference, and not to the object referenced. Therefore, the object being referenced can still be modified through that reference, even inside a const member function, like the one above.
Note that, references can't be assigned after initialization anyway, so it really doesn't change what you can do with that reference.
Perhaps a pointer analogy will help.
Let's say you have:
struct Foo
{
Foo(int* cnt) : cnt_(cnt) {}
void test1() const
{
*cnt_ = 0;
}
void test2(int* p) const
{
cnt_ = p; // Not allowed
}
int* cnt_;
};
In test1, you are not changing cnt_. You are changing the value of cnt_ points to. That is allowed.
In test2, you are changing cnt_. That is not allowed.
In your case, you are not changing cnt_ to reference another object. You are changing the value of the object cnt_ references. Hence, it is allowed.
Update: I'm looking to see if there's a way to zero-initialize the entire class at once, because technically, one can forget adding a '= 0' or '{}' after each member. One of the comments mentions that an explicitly defaulted no-arg c-tor will enable zero-initialization during value-initialization of the form MyClass c{};. Looking at http://en.cppreference.com/w/cpp/language/value_initialization I'm having trouble figuring out which of the statements specify this.
Initialization is a complex topic now since C++11 has changed meaning and syntax of various initialization constructs. I was unable to gather good enough info on it from other questions. But see, for example, Writing a Default Constructor Forces Zero-Initialization?.
The concrete problem I'm facing is: I want to make sure members of my classes are zeroed out both for (1) classes which declare a default c-tor, and for (2) those which don't.
For (2), initializing with {} does the job because it's the syntax for value-initialization, which translates to zero-initialization, or to aggregate initialization if your class is an aggregate - case in which members for which no initializer was provided (all!) are zero-initialized.
But for (1) I'm still not sure what would be the best approach. From all info I gather I learned that if you provide a default c-tor (e.g. for setting some of the members to some values), you must explicitly zero remaining members, otherwise the syntax MyClass c = MyClass(); or the C++11 MyClass c{}; will not do the job. In other words, value-initialization in this case means just calling your c-tor, and that's it (no zero-ing).
You run into the same situation if you declare a c-tor that takes values, and sets those values to a subset of the members, but you'd like other members to be zero-ed: there is no shorthand for doing it - I'm thinking about 3 options:
class MyClass
{
int a;
int b;
int c;
MyClass(int a)
{
this->a = a;
// now b and c have indeterminate values, what to do? (before setting 'a')
// option #1
*this = MyClass{}; // we lost the ability to do this since it requires default c-tor which is inhibited by declaring this c-tor; even if we declare one (private), it needs to explicitly zero members one-by-one
// option #2
std::memset(this, 0, sizeof(*this)); // ugly C call, only works for PODs (which require, among other things, a default c-tor defaulted on first declaration)
// option #3
// don't declare this c-tor, but instead use the "named constructor idiom"/factory below
}
static MyClass create(int a)
{
MyClass obj{}; // will zero-initialize since there are no c-tors
obj.a = a;
return obj;
}
};
Is my reasoning correct?
Which of the 3 options would you choose?
What about using in-class initialization?
class Foo
{
int _a{}; // zero-it
int _b{}; // zero-it
public:
Foo(int a): _a(a){} // over-rules the default in-class initialization
};
Option 4 and 5:
option 4:
MyClass(int a) :a(a), b(0), c(0)
{
}
option 5:
class MyClass
{
int a = 0;
int b = 0;
int c = 0;
MyClass(int a) : a(a) {
}
}
In my humble opinion, the simplest way to ensure zero-initialization is to add a layer of abstraction:
class MyClass
{
struct
{
int a;
int b;
int c;
} data{};
public:
MyClass(int a) : data{a} {}
};
Moving the data members into a struct lets us use value-initialization to perform zero-initialization. Of course, it is now a bit more cumbersome to access those data members: data.a instead of just a within MyClass.
A default constructor for MyClass will perform zero-initialization of data and all its members because of the braced-initializer for data. Additionally, we can use aggregate-initialization in the constructors of MyClass, which also value-initializes those data members which are not explicitly initialized.
The downside of the indirect access of the data members can be overcome by using inheritance instead of aggregation:
struct my_data
{
int a;
int b;
int c;
};
class MyClass : private my_data
{
MyClass() : my_data() {}
public:
MyClass(int a) : MyClass() { this->a = a; }
};
By explicitly specifying the base-initializer my_data(), value-initialization is invoked as well, leading to zero-initialization. This default constructor should probably be marked as constexpr and noexcept. Note that it is no longer trivial. We can use initialization instead of assignment by using aggregate-initialization or forwarding constructors:
class MyClass : private my_data
{
public:
MyClass(int a) : my_data{a} {}
};
You can also write a wrapper template that ensures zero-initialization, thought the benefit is disputable in this case:
template<typename T>
struct zero_init_helper : public T
{
zero_init_helper() : T() {}
};
struct my_data
{
int a;
int b;
int c;
};
class MyClass : private zero_init_helper<my_data>
{
public:
MyClass(int a) { this->a = a; }
};
Having a user-provided constructor, zero_init_helper no longer is an aggregate, hence we cannot use aggregate-initialization any more. To use initialization instead of assignment in the ctor of MyClass, we have to add a forwarding constructor:
template<typename T>
struct zero_init_helper : public T
{
zero_init_helper() : T() {}
template<typename... Args>
zero_init_helper(Args&&... args) : T{std::forward<Args>(args)...} {}
};
class MyClass : private zero_init_helper<my_data>
{
public:
MyClass(int a) : zero_init_helper(a) {}
};
Constraining the constructor template requires some is_brace_constructible trait, which is not part of the current C++ Standard. But this already is a ridiculously complicated solution to the problem.
It is also possible to implement your option #1 as follows:
class MyClass
{
int a;
int b;
int c;
MyClass() = default; // or public, if you like
public:
MyClass(int a)
{
*this = MyClass{}; // the explicitly defaulted default ctor
// makes value-init use zero-init
this->a = a;
}
};
What about constructor delegation?
class MyClass
{
int a;
int b;
int c;
MyClass() = default; // or public, if you like
public:
MyClass(int a) : MyClass() // ctor delegation
{
this->a = a;
}
};
[class.base.init]/7 suggests that the above example shall invoke value-initialization, which leads to zero-initialization since the class does not have any user-provided default constructors [dcl.init]/8.2. Recent versions of clang++ seem to zero-initialize the object, recent versions of g++ do not. I've reported this as g++ bug #65816.