Access to class inside Union - c++

I have the declaration of class Ainside a third party library, so I can't modify it.
I need to use the declaration of class B to pass it to a method, is there a way to do it without modifying class A?
When I try this:
#include <iostream>
using namespace std;
class A
{
public:
union {
class B
{
public:
int x;
};
}un;
};
void foo(A::B & test)
{
}
int main() {
A::B test;
test.x=10;
cout << test.x << endl;
return 0;
}
I get the error:
error: B is not a member of A
Live Example!
My assumption is that it happens because B is in a unnamed namespace.
PS: If I could modify the declaration of the union
from:
union {...
to:
union T {...
This will be done simple by:
A::T::B test;

You can get the type of the union using decltype, then you can access B:
decltype(std::declval<A&>().un)::B test;
coliru example

Related

class field with a type defined in an anonymous namespace

I have a struct defined in an anonymous namespace. Then I also want to have a class defined which has a field of that struct type.
I forward declare the struct in the header file:
struct my_str;
class my_class {
public:
struct my_str *field;
void method();
};
and then in the cpp file I have the actual type defined and some methods using it:
namespace {
struct my_str {
int data;
};
}
void helper(struct my_str * obj) {
std::cout << obj->data;
}
void my_class::method() {
helper(field);
}
This doesn't compile:
test.cc:10:20: error: reference to ‘my_str’ is ambiguous
It lists 2 definitions for my_str, the forward declaration and the one from the anonymous namespace.
Is there a way to disambiguate and make this compile?
An anonymous namespace hides the name from the outside, so you can't use that - there is no way for an outsider to refer to that type.
You don't need to write the definition in an anonymous namespace - it is hidden outside anyway.
However, this will lead to undefined behaviour if you have another global type with the same name, due to the One Definition Rule.
Probably the best solution is to hide the definition inside my_class instead:
Header:
class my_class {
public:
// Note the separate declaration; a one-liner would declare
// that there is a global `my_str`.
struct my_str; // Not defined for the outside world, but the name is accessible.
my_str *field;
void method();
};
Source:
struct my_class::my_str
{
int data;
};
namespace
{
void helper(my_data::my_str* obj) {
std::cout << obj->data;
}
}
void my_class::method() {
helper(field);
}
I came up with this approach and would like to hear what people think.
"every problem in computer science can be solved by adding another level of indirection"
.h:
struct my_str_wrap;
class my_class {
public:
struct my_str_wrap* field;
void method();
};
.cc:
namespace {
struct my_str {
int data;
};
}
struct my_str_wrap {
struct my_str w;
};
void helper(struct my_str& obj) {
std::cout << obj.data;
}
void my_class::method() {
helper(field->w);
}

How to access correct class member?

I've been running across this snippet of code and after execution I found out that everything compiles and executes fine (the int code member of the derived class is set to 65). However I was wondering how would one be able to access the char code member of the derived class?
#include <iostream>
using namespace std;
class base {
public:
base() : code('B') { }
char code;
};
class derived : public base
{
public:
int code;
};
int main(void)
{
derived d;
d.code = 65;
std::cout << d.code;
};
By specifying the correct scope for the base member variable using a qualified name lookup, as follows:
d.base::code = 'x'
std::cout << d.base::code << '\n';
See this section on qualified name lookups for more details.

What happens to a variable of a member function having same name as that of a private data member of the same class?

When i compile the code below i don't get any error and on debugging it initializes the class data member a of class
abc to zero. Can someone just tell me how is the compiler differentiating between the two. I dont see it happening in runtime.
//A function friendly to two classes (finding maximum of objects of 2 classes(one data member in class)
#include <iostream>
#include <conio.h>
using namespace std;
class abc; //Forward Declaration
class xyz
{
int x;
public :
void inivalue(float);
friend float max(xyz,abc);
};
class abc
{
int a;
public :
void inivalue(float);
friend float max(xyz,abc);
};
void xyz::inivalue(float y)
{
x=y;
}
void abc::inivalue(float a)
{
a=a;
}
float max(xyz m,abc n)
{
if(m.x > n.a)
return m.x;
else
return n.a;
}
int main()
{
system("cls");
xyz o1;
abc o2;
o1.inivalue(10);
o2.inivalue(20);
cout<<"The maximum of 2 classes is : "<<max(o1,o2)<<endl;
}
That's called "variable shadowing".
When you do that, the local variable a "shadows" the class variable. The compiler will use the local variable, so in the inivalue function of the class abc you're just setting the parameter value to itself.
The a member of the class is unitialized when it is used in the max and the code will result in Undefined Behaviour.

C++'s double colon used after a class name instead of a namespace

I am trying to understand a c++ program listed here. I am confused about the second use of double colons on lines 86-87:
using TransformType = itk::AffineTransform< ScalarType, Dimension >;
TransformType::Pointer transform = TransformType::New();
It looks like TransformType is a user-defined type. How would one use it before New()? I heard that the double-colon is to be used following a namespace, but here, TransformType is a type (namely class) rather than a namespace. Can someone clarify --- should double colon be always used after a namespace in C++? Would it possible to use a dot (like in Java) instead?
You use the scope resolution operator (::) to name something in a namespace, or in a class, or in a scoped enum; this is called qualified lookup.
#include <iostream>
namespace N
{
int x = 0;
}
int main()
{
std::cout << N::x << '\n';
}
Using it with a class usually means you're referring to some static member, because otherwise you'd generally be using objectInstance.member instead.
#include <iostream>
class C
{
public:
static int x;
}
int C::x = 0;
int main()
{
std::cout << C::x << '\n';
}
Though, within a non-static member function, there are still uses for ::, such as disambiguating between names that exist concurrently in different bases.
class Base
{
public:
void foo() {}
};
class Derived : public Base
{
public:
void foo()
{
// Do base version (omitting Base:: will just call this one again!)
Base::foo();
// Now maybe do other things too
}
};
int main()
{
Derived obj;
obj.foo();
}
… or for naming a non-static member in a scenario where an object context is not required:
#include <iostream>
class C
{
public:
int x;
}
int main()
{
std::cout << sizeof(C::x) << '\n';
decltype(C::x) y = 42;
}
It's needed with scoped enums because, well, they're scoped; that's the whole point of them. They don't leak into the surrounding scope but have their own which as a result you need to specify specifically.
enum class E
{
Alpha,
Bravo,
Charlie
};
void foo(E value) {}
int main()
{
foo(E::Alpha);
}
Some languages let you access static members of classes with the type name followed by ., just like you'd access non-static members of classes with the object name followed by .. C++ is not one of those languages.
By the way, this is legal:
#include <iostream>
class C
{
public:
int x = 42;
};
int main()
{
C obj;
std::cout << obj.C::x << '\n';
// ^^^ what?!
}
Adding scope resolution to x here is not necessary, because the language already knows from the obj. that you're asking for a member of a class C. But you can still add it if you want. It's just usually "done for you" in this case.

Shorten Member Function Scope Specifiers (Nested Classes) (C++)

Suppose I have nested classes as follows defined in a header file:
class ClassA
{
private:
class ClassB
{
private:
int member_b;
public:
void function_name();
};
};
In order to give a definition to the function "function_name()" in an external .cpp file, I have to access it like this:
void ClassA::ClassB::function_name()
{
std::cout << member_b;
return;
}
For the sake of this example, please do not ask why I'm using nested classes; I have a reason for doing so in my actual project. However, my question is this; is it possible to somehow shorten the ClassA::ClassB::function_name() in the implementation file to something like short::function_name() while still keeping the classes nested? I don't think that typedefs or new namespace definitions can help me here, but maybe I'm wrong.
Qualified type names allow you to define a typedef to represent a qualified class name. You can then use the typedef with the :: (scope resolution) operator to refer to a nested class or class member, as shown in the following example:
class outside
{
public:
class nested
{
public:
static int x;
static int y;
int f();
int g();
};
};
int outside::nested::x = 5;
int outside::nested::f() { return 0; };
typedef outside::nested outnest; // define a typedef
int outnest::y = 10; // use typedef with ::
int outnest::g() { return 0; };
However, using a typedef to represent a nested class name hides information and may make the code harder to understand.
Source : https://www.ibm.com/support/knowledgecenter/en/SSPSQF_9.0.0/com.ibm.xlcpp111.aix.doc/language_ref/cplr061.html
Have you tried using aliases?
// C++11
using fmtfl = std::ios_base::fmtflags;
// C++03 equivalent:
// typedef std::ios_base::fmtflags fmtfl;
fmtfl fl_orig = std::cout.flags();
fmtfl fl_hex = (fl_orig & ~std::cout.basefield) | std::cout.showbase | std::cout.hex;
// ...
std::cout.flags(fl_hex);
Code source: https://msdn.microsoft.com/en-us/library/dn467695.aspx