I saw this question on SO and wondered where this kind of code can actually be used in the real time example.
struct a
{
static struct a b;
};
int main()
{
a::b;
return 0;
}
Also what is the significance of a::b;
Thanks for your inputs.
Such code can be used in implementation of the Singleton pattern. Here, one instance of type a is declared; if other instances are somehow forbidden, it is the singleton. In practice, however, i recall, they usually use less confusing syntax.
And, as for a::b, it does nothing useful. It just shows the name of the instance. A more useful example would be this:
struct a
{
static struct a b;
int data;
};
a a::b = {9};
int main()
{
int stuff = a::b.data;
printf("%d\n", stuff);
return 0;
}
Related
When and why should we use the 'struct' keyword when declaring a class pointer variable in C++?
I've seen this in embedded environments so I suspect that this is some kind of hold over from C. I've seen plenty of explanations on when to use the 'struct' keyword when declaring a struct object as it relates to namespaces in C (here), but I wasn't able to find anyone talking about why one might use it when declaring a class pointer variable.
Example, in CFoo.h:
class CFoo
{
public:
int doStuff();
};
inline Foo::doStuff()
{
return 7;
}
And later in a different class:
void CBar::interesting()
{
struct CFoo *pCFoo;
// Go on to do something interesting with pCFoo...
}
There's rarely a reason to do this: it's a fallover from C and in this case the programmer is simply being sentimental - perhaps it's there as a quest for readability. That said, it can be used in place of forward declarations.
In some instances you might need to disambiguate, but that's not the case here. One example where disambiguation would be necessary is
class foo{};
int main()
{
int foo;
class foo* pf1;
struct foo* pf2;
}
Note that you can use class and struct interchangeably. You can use typename too which can be important when working with templates. The following is valid C++:
class foo{};
int main()
{
class foo* pf1;
struct foo* pf2;
typename foo* pf3;
}
There are two reasons to do this.
The first one is if we are going to introduce a new type in the scope using an elaborated name. That is in this definition
void CBar::interesting()
{
struct CFoo *pCFoo;
// Go on to do something interesting with pCFoo...
}
the new type struct CFoo is introduced in the scope provided that it is not yet declared. The pointer may point to an incomplete type because pointers themselves are complete types.
The second one is when a name of a class is hidden by a declaration of a function or a variable. In this case we again need to use an elaborated type name.
Here are some examples
#include <iostream>
void CFoo( const class CFoo * c ) { std::cout << ( const void * )c << '\n'; }
class CFoo
{
public:
int doStuff();
};
int main()
{
class CFoo c1;
return 0;
}
Or
#include <iostream>
class CFoo
{
public:
int doStuff();
};
void CFoo( void ) { std::cout << "I am hidding the class CGoo!\n"; }
int main()
{
class CFoo c1;
return 0;
}
In C, two different styles are the most common:
typedef struct { ... } s; with variables declared as s name;.
struct s { ... }; with variables declared as struct s name;
In C++ you don't need to typedef to omit the struct keyword, so the former style is far more in line with the C++ type system and classes, making it the most common style in C++.
But then there are not many cases in C++ when you actually want to use struct instead of class in the first place - structs are essentially classes with all members public by default.
The reason for this may be as simple as not having to include a header file whose contents aren't needed other than for announcing that CFoo names a type. That's often done with a forward declaration:
class CFoo;
void f(CFoo*);
but it can also be done on the fly:
void f(struct CFoo*);
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
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(){
x=0;
}
A(int i)
{
x=i;
}
int Get_x(){
return x;
}
};
class B{
private:
A objA(1);
public:
objA.Get_x();
};
This is my code and it has two classes i.e A and B ..First class runs fine but in class B ..compiler gives the syntax error in the declaration of objB.....But as far as i know it should be correct ...so plz help ....thanks
This initialization is invalid for a data member:
A objA(1);
You need
A objA{1};
or
A objA = A(1);
Besides that, this kind of statement can only happen inside of a function:
objA.Get_x();
The compiler is trying to interpret A objA(1) as a function declaration, which is wrong. You may declare objA as A objA = A(1); (please note that thi is a C++11 feature, you may need to enable it before).
Also, I don't really know what objA.Get_x() should do, but this is also wrong, you can't just access a member outside of a function. Probably, you meant this:
int Get_x() {
return objA.Get_x();
}
How could I make a function only seen by the function that calls it?
define the function I want to hide as private function is not enough, as it could still be seen by other public functions in the class.
Now I use lambda expression to define anonymous function inside function. Is there any better solution?
Aside from using a lambda (which you've rejected), you could implement your function in its own compilation unit, and code the supporting function in an anonymous namespace within that compilation unit.
But that supporting function would be outside the class, so you'd have to pass it all the parameters it needed. That could become unwieldly though no worse than a long lambda capture list.
You can use a function object. For example(you can compile this, even in C++03):
#include <iostream> // only for output
class foo{
int bar(){return 0;} // Only foo can see this
public:
int operator()(){
return bar();
}
};
class baz{
public:
foo do_foo;
};
int main(){
baz a;
std::cout << a.do_foo() << std::endl;
}
the method bar is only visible by a foo.
P.S.: If you need foo to access members of baz, make it a friend.
A simmilar approach to cassiorenan would be to use static class functions and friends.
Something like this:
void Boss();
class Worker {
static void Test(){ return;}
friend void Boss();
};
void Boss(){
Worker::Test();
}
Though why would you want to do this, I don't know.
It is possible to define function inside a function without lambdas. Just define a struct that contains required function. This approach is not much better than using lambda, but at least this is straightforward and works with older compilers too.
int func() {
struct {
int hiddenFunc() {
return 1;
}
} h;
int a = h.hiddenFunc() + h.hiddenFunc();
return a;
}
As a slight variation from cassiorenan's solution, you could use a class containing one public static function (the visible function) and one static private function that could only be called from there. To avoid creation of objects of that class, it is enough to put a private constructor.
EDIT:
Per cassiorenan's comment, I can see that OP really needs methods and not functions. In that case, I would still use a dedicated class in a anonymous namespace to ensure it is not visible from elsewhere (even if my example is single file ...) friend to the class really used. So in below example, bar is the business class that would have a method with an externally hidden implementation (here relay_method), and foo is dedicated to the hidden method called with a pointer to the real object. In real world, the whole anonymous namespace and the implementation of the hidden method should be in the implementation file bar.cpp.
That way, the real implementation function priv_func can only be called from a bar object through bar::relay_method() and foo::bar_func(bar &).
#include <iostream>
class bar;
namespace {
class foo {
private:
static int priv_func(int i) {
return i * i;
}
foo() {}
public:
// only useful if true functions were needed
/* static int pub_func(int i, int j) {
return priv_func(i) + priv_func(j);
}*/
static void bar_func(bar& b);
};
}
class bar {
int x;
int x2;
public:
bar(int i): x(i) {}
void relay_method() {
foo::bar_func(*this);
}
friend class foo;
int getX2() const {
return x2;
}
};
void foo::bar_func(bar& b) {
b.x2 = foo::priv_func(b.x);
}
using namespace std;
int main() {
/* int i = foo::pub_func(3,4);
cout << i << endl;
// foo::priv_func(2); error access to private member of class foo
// foo f; */
bar b(2);
b.relay_method();
cout << b.getX2() << endl;
return 0;
}
Can a struct have a constructor in C++?
I have been trying to solve this problem but I am not getting the syntax.
In C++ the only difference between a class and a struct is that members and base classes are private by default in classes, whereas they are public by default in structs.
So structs can have constructors, and the syntax is the same as for classes.
struct TestStruct {
int id;
TestStruct() : id(42)
{
}
};
All the above answers technically answer the asker's question, but just thought I'd point out a case where you might encounter problems.
If you declare your struct like this:
typedef struct{
int x;
foo(){};
} foo;
You will have problems trying to declare a constructor. This is of course because you haven't actually declared a struct named "foo", you've created an anonymous struct and assigned it the alias "foo". This also means you will not be able to use "foo" with a scoping operator in a cpp file:
foo.h:
typedef struct{
int x;
void myFunc(int y);
} foo;
foo.cpp:
//<-- This will not work because the struct "foo" was never declared.
void foo::myFunc(int y)
{
//do something...
}
To fix this, you must either do this:
struct foo{
int x;
foo(){};
};
or this:
typedef struct foo{
int x;
foo(){};
} foo;
Where the latter creates a struct called "foo" and gives it the alias "foo" so you don't have to use the struct keyword when referencing it.
As the other answers mention, a struct is basically treated as a class in C++. This allows you to have a constructor which can be used to initialize the struct with default values. Below, the constructor takes sz and b as arguments, and initializes the other variables to some default values.
struct blocknode
{
unsigned int bsize;
bool free;
unsigned char *bptr;
blocknode *next;
blocknode *prev;
blocknode(unsigned int sz, unsigned char *b, bool f = true,
blocknode *p = 0, blocknode *n = 0) :
bsize(sz), free(f), bptr(b), prev(p), next(n) {}
};
Usage:
unsigned char *bptr = new unsigned char[1024];
blocknode *fblock = new blocknode(1024, btpr);
Class, Structure and Union is described in below table in short.
Yes, but if you have your structure in a union then you cannot. It is the same as a class.
struct Example
{
unsigned int mTest;
Example()
{
}
};
Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.
In c++ struct and c++ class have only one difference by default struct members are public and class members are private.
/*Here, C++ program constructor in struct*/
#include <iostream>
using namespace std;
struct hello
{
public: //by default also it is public
hello();
~hello();
};
hello::hello()
{
cout<<"calling constructor...!"<<endl;
}
hello::~hello()
{
cout<<"calling destructor...!"<<endl;
}
int main()
{
hello obj; //creating a hello obj, calling hello constructor and destructor
return 0;
}
Yes. A structure is just like a class, but defaults to public:, in the class definition and when inheriting:
struct Foo
{
int bar;
Foo(void) :
bar(0)
{
}
}
Considering your other question, I would suggest you read through some tutorials. They will answer your questions faster and more complete than we will.
Note that there is one interesting difference (at least with the MS C++ compiler):
If you have a plain vanilla struct like this
struct MyStruct {
int id;
double x;
double y;
} MYSTRUCT;
then somewhere else you might initialize an array of such objects like this:
MYSTRUCT _pointList[] = {
{ 1, 1.0, 1.0 },
{ 2, 1.0, 2.0 },
{ 3, 2.0, 1.0 }
};
however, as soon as you add a user-defined constructor to MyStruct such as the ones discussed above, you'd get an error like this:
'MyStruct' : Types with user defined constructors are not aggregate
<file and line> : error C2552: '_pointList' : non-aggregates cannot
be initialized with initializer list.
So that's at least one other difference between a struct and a class. This kind of initialization may not be good OO practice, but it appears all over the place in the legacy WinSDK c++ code that I support. Just so you know...
One more example but using this keyword when setting value in constructor:
#include <iostream>
using namespace std;
struct Node {
int value;
Node(int value) {
this->value = value;
}
void print()
{
cout << this->value << endl;
}
};
int main() {
Node n = Node(10);
n.print();
return 0;
}
Compiled with GCC 8.1.0.
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
I'd rather initialize inside the constructor so I don't need to keep the order.
Syntax is as same as of class in C++. If you aware of creating constructor in c++ then it is same in struct.
struct Date
{
int day;
Date(int d)
{
day = d;
}
void printDay()
{
cout << "day " << day << endl;
}
};
Struct can have all things as class in c++. As earlier said difference is only that by default C++ member have private access but in struct it is public.But as per programming consideration Use the struct keyword for data-only structures. Use the class keyword for objects that have both data and functions.
Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default. Anything you can do in a class you should be able to do in a structure.
struct Foo
{
Foo()
{
// Initialize Foo
}
};
Yes it possible to have constructor in structure here is one example:
#include<iostream.h>
struct a {
int x;
a(){x=100;}
};
int main() {
struct a a1;
getch();
}
In C++ both struct & class are equal except struct'sdefault member access specifier is public & class has private.
The reason for having struct in C++ is C++ is a superset of C and must have backward compatible with legacy C types.
For example if the language user tries to include some C header file legacy-c.h in his C++ code & it contains struct Test {int x,y};. Members of struct Test should be accessible as like C.
In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it.
The only difference is the default scope of the variables/functions defined.
Other than the above difference, mostly you should be able to imitate the functionality of class using structs.