If you have a anonymous struct in a class with external linkage(under public access). Will that struct be a different entity in each file?
same goes for const data members?
class k{
public:
struct {int u;} o;
}a;
I am not sure if I get your question (also I strongly discourage you to use something like that in your class)
Anyway each instance of class k will get their own copy of your struct o.
Also, your struct is not anonymous, but it's unnamed #DyP. You usually want to use anonymous struct/union when they are nested (and more specifically you are supposed to use anonymous union).
Example1:
struct T {
int tag;
union { float x; int n; };
};
Related
The STL <memory> header (MSVC implementation) contains a class called:
template <class _Ty> class _Ref_count_obj2 : public _Ref_count_base
This class has a member:
union {
_Wrap<_Ty> _Storage;
};
where _Wrap is defined as:
template <class _Ty>
struct _Wrap {
_Ty _Value; // workaround for "T^ is not allowed in a union"
};
From my understanding, this code is designed to hold an object of type _Ty following its construction via the new operator. However I can't figure out why this was done; it seems like using a struct instead of a struct inside a union would work just as well.
Can anyone explain the reasoning behind this? Also, can anyone explain the comment in the _Wrap definition?
First, embedding the _Storage member in a union will prevent default destruction of that object (which is, more than likely, a non-trivial type); this appears to be essential, as the class involved is a reference counter. (By default, unions have a deleted destructor; see, for example: Is a Union Member's Destructor Called .)
Second, using an anonymous union 'moves' the _Storage identifier into the enclosing scope, thus removing any need for X.-style notation (if the union were to be named X). From cppreference:
Members of an anonymous union are injected in the enclosing scope (and
must not conflict with other names declared there).
Last, the need to wrap the union's member into a templated structure is so that the class will work with reference types, which are not allowed in unions. To check this last part out, try the following code with the commented-out lines made active:
template <class _Ty>
struct _Wrap {
_Ty _Value; // workaround for "T^ is not allowed in a union"
};
template<class T>
class bob {
public:
bob(T t) : uncle{t}//, aunty(t)
{
}
private:
union {
_Wrap<T> uncle;
};
// union {
// T aunty;
// };
};
int main()
{
int i = 42;
bob<int&> b{ i }; // Note: Template uses a REFERENCE type
return 0;
}
What I want is for some class members to be sometimes private and others times public. These members are supposed to be accessible by some modules and inaccessible by others.
Imaging this class:
class Foo {
public:
...
private:
...
protected:
...
internal:
int x;
};
In module X the internal is defined as:
#define internal public
and in module Y it's defined as:
#define internal private
So the real question is if this trick is acceptable by the standard or if it will change the signature of the class (or its members) in any way.
I know that friend and PIMPL are for this kind of job but friend can get extremely messy and PIMPL's performance (an indirection and the fact that you can't inline) are not acceptable for the codebase I'm working on.
It is an ODR violation and hence invokes undefined behaviour. (See also basic.def.odr]/6.1 "each definition of D shall consist of the same sequence of tokens").
However, a common implementation is that public, private, protected have no impact on class layout so it will work.
You are skating on thin ice; there is nothing to stop a compiler putting all the public members first, then the protected ones, then the private ones. More to the point, in general, the order of declaration is required to be the order in memory so
struct T {char a; int b; char c};
is required to have a, then b, then c. This is to ensure C compatability. However, there is no requirement on the ordering of elements with different access (See [class.mem]/9.2 p13: "Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (Clause 11)". So given
struct T {char a; int b; private: char c};
the compiler can reorder the members and put c in the gap between a and b.
Final note to EJP and others who think these are declarations not defintions: I have given two definitions of T above; a declaration would look like struct T;.
Edit: Thanks to Fanael for the cite from the standard.
The C++ originally seemed to consider that private members could be placed somewhere other than next to public members, perhaps so they could be a protected region in hardware, so it is conceivable that the public and private sections could be moved relative to each other.
It is possible to test your code without redefining public / private using tricks by Herb Stutter GOTW 76 and completed to a fully functional system with this data here litb safer private member access
Given a class as follows....
struct A {
A(int a):a(a) { }
private:
int a;
};
A class robber is required...
template<typename Tag, typename Tag::type M>
struct Robber {
friend typename Tag::type get(Tag) {
return M;
}
};
A utility class allowing multiple steals....
template<typename Tag, typename Member>
struct TagBase {
typedef Member type;
friend type get(Tag);
};
Declaring a theft intent becomes
struct A_f : TagBase<A_f, int A::*> { };
template struct Robber<A_f, &A::a>;
Then stealing the data....
int main() {
A a(42);
std::cout << "proof: " << a.*get(A_f()) << std::endl;
}
This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 8 years ago.
For classes, you could just say:
class Test{
int a;
Test(int a);
}
Test::Test(int a) {
this->a=a;
}
Function names get "classname::" in front of them when declared outside of class.
How would I do this for structs?
struct Test {
int a;
Test(int a);
}
How would I write the function for this struct Test outside of struct declaration so that it can be only be called by a Test struct?
Same way. Difference between struct and class in C++ is only default visibility of members (private for class, public for struct).
Actually, it's not just function, it's constructor of class/struct Test.
In C++, structs are essentially the same as classes except for their default protection levels: classes default to private, structs to public. To define that function outside of the struct so that it can only be called from a member, declare it as private, then define it as normal:
struct Test {
private:
int a;
Test(int a);
};
Test::Test(int a) {
this->a=a;
}
Additionally, instead of modifying the a member in the constructor body like that, you should use an initializer list. This sets the value of the member before the instance is fully constructed. It's not so important with just an int, but it's a good practice to get in to.
struct Test {
private:
Test(int a) : a(a) {}
int a;
};
How would I write the function for this struct Test outside of struct declaration
Do exactly what you did for the first one. Both are class types, whether you use the class or struct keyword to introduce them.
The only difference is the default accessibility of members and base classes: private if you use class, and public if you use struct.
so that it can be only be called by a Test struct?
If you mean that you want it to be private (as it is in the first example), then you'll have to do so explicitly, since accessibility defaults to public:
struct Test {
int a;
private:
Test(int a);
};
Personally, I'd use the more conventional class if there's anything non-public.
ForEveR is right. Just like in the question you can have a structure member defined like:
struct Test{
int a;
Test(int a);
};
Test::Test(int a) {
this->a=a;
}
point to note, struct members are public by default. class memebers are private by default.
I am wondering if a struct has the same idea as enum in c++? If someone can explain similarities/differences I will be grateful I am trying to learn.
Are struct in c++ similar to enum or classes?
In C++, a struct is essentially the same as a class, except that the default access modifiers for member variables, methods, and for base classes are all public, where in a class, the default access modifier is private.
struct is basically a class with all members public.
For instance:
struct MyNewStruct {
int myNewInt;
double myNewDouble;
};
is equivalent to:
class MyNewClass {
public:
int myNewInt;
double myNewDouble;
};
Hence, you can create a struct with constructor:
struct MyNewStruct {
int myNewInt;
double myNewDouble;
MyNewStruct(int i, double d)
: myNewInt(i), myNewDouble(d)
{}
};
An enum is for abstracting away magic numbers.
A struct is for holding a collection of different variables.
You can almost think of an enum as a stand-in for an int or char to make things more readable.
Sorry for naive question in C++. For below code, there is a class, inside which there is a union declaration having two variables. How to access the variables in the union using the class object in code below:
class my
{
public:
//class member functions, and oeprator overloaded functions
public:
union uif
{
unsigned int i;
float f;
};
private:
//some class specific variables.
};
if there is an object of type my defined like
my v1;
in a function later
Using v1 how do i access float f; inside union above in code?
also I want to watch the value of this float f in the watch window of a debugger(VS-2010), how to do that?
I tried v1.uif.f , this gave error in the watch window as : Error oeprator needs class struct or union.
v1.
You are only defining the union within the scope of the class, not actually creating a member variable of its type. So, change your code to:
class my
{
public:
//class member functions, and oeprator (sic) overloaded functions
public:
union uif
{
unsigned int i;
float f;
} value;
private:
//some class specific variables.
};
Now you can set the member variables in your union member, as follows:
my m;
m.value.i=57;
// ...
m.value.f=123.45f;
You never actually defined any member of that union. You only ever defined the union itself. There is no spoon float.
You've only defined the type of the uniion, you've not yet declared an object of this union type.
Try this:
class my
{
public:
union uif
{
unsigned int i;
float f;
};
uif obj; //declare an object of type uif
};
my v;
v.obj.f = 10.0; //access the union member
One option I don't see already here is that of an Anonymous Union, which is where you have no type or instantiation. Like so:
class my
{
public:
//class member functions, and oeprator (sic) overloaded functions
function(int new_i) { i = new_i;}
function(float new_f) { f = new_f;}
public:
union /* uif */
{
unsigned int i;
float f;
};
private:
//some class specific variables.
};
my m;
m.i=57;
m.f=123.45f;
Remember that with unions, it is only defined to read from the last member variable written to.
You have defined your union in your class, but you haven't created an instance of it! Try:
union uif
{
unsigned int i;
float f;
} myUif;
And then use v1.myUif.f (or i).