The question is simple, I guess I cannot do this: (Im in the header file)
typedef struct {
myclass *p;
...
} mystruct;
class myclass {
private:
mystruct *s;
...
}
Because when the compiler reaches the struct it doesnt know what myclass is, but I cannot do the reverse either for the same reason:
class myclass {
private:
mystruct *s;
...
}
typedef struct {
myclass *p;
...
} mystruct;
How can I make that possible ? Im guessing there is some way to say the compiler "There is an struct called mystruct" before the class (2 example) so it knows that mystruct *s it's possible but I cant manage to do it right. Thanks
You need to use a forward declaration:
class myclass;
typedef struct {
myclass *p;
...
} mystruct;
class myclass {
private:
mystruct *s;
...
}
Now the compiler knows that myclass is a class when it first sees it.
Also, no need to typedef structs in C++. You can simply write:
struct mystruct {
myclass *p;
...
};
Which does the same.
In general, it is possible to declare a pointer to a class that has not been defined yet. You need only to have "declared" the class (class myclass).
This is the general solution to define classes with cross-references.
First of all, typedefs shouldn't be used anymore in modern C++ (there is better syntax). For structs just use:
struct mystruct {
...
}
Also maybe consider a redesign so that you don't have 2 types dependent on each other. If it's not possible, then as others have said forward declare the types before.
I'm working on a project with a pre-made .hpp file with all the declarations and stuff.
A struct is declared in the private part of the class, along with some private members.
I need to create an array with the type of the struct in my .cpp file.
//.hpp
private:
struct foo
{
std::string a;
unsigned int b;
};
std::string* x;
unsigned int y;
//.cpp
unsigned int returny()
{
return y; // No errors
}
foo newArray[10]; // Compile time error; unknown type name
Why is it that I can return y, which is also private, but not make an array out of the struct foo?
How can I fix this? (I'm in an introductory C++ class... so hopefully there's a simple solution)
There are couple of issues.
You can't use a type that's defined in the private section of class like you are trying.
The nested type can be used by specifying the appropriate scope.
EnclosingClass::foo newArray[10];
But this will work only if foo is defined in the public section of EnclosingClass.
you should define the struct int the outside of the class like this
struct Foo
{
std::string a;
unsigned int b;
};
class A {
private:
Foo foo;
...
}
My lecturer just astounded me by insisting that the following is a valid C++ statement:
struct charlistrecord *next
The complete condition was found in declaring a recursive datatype in C/C++ as follows:
typedef struct charlistrecord
{
char data;
struct charlistrecord *next;
} *charlist;
I want to know whether maybe there has been a time when this was accepted syntax or whether I've just been dumb for months of thinking I know C++.
Prior to C++ and the assumption of typedefs, the only way to get a typed structure was via this syntax, and it was the only way to get a self-type-linked node.
struct Foo
{
int val;
struct Foo *link;
};
In C, this required any usage of Foo to be:
struct Foo foo;
struct Foo *foo_ptr;
etc..
A typedef helped for this by doing this:
typedef struct Foo
{
int val;
struct Foo *link;
} Foo;
Since now you could do this:
Foo foo; // same as struct Foo
Foo *foo_ptr; // same as struct Foo *
Note: Using a typedef to alias a struct Name is not restricted to Name as the alias. Yo were perfectly valid to do this as well:
typedef struct Foo
{
int val;
struct Foo *link;
} Bar;
and now the following are doable;
struct Foo foo;
Bar bar;
struct Foo *fooptr = &bar;
Bar *barptr = &foo;
Really makes you wish you programmed in C back in the day, doesn't it ? Probably doesn't clear things up, but hopefully a little less gray.
It's a hangover from C. In C this is how you have to declare struct variables and members, so it's legal in C++ for reasons of backwards compatibility. Sounds like your lecturer is a bit 'old school'.
Yes it's totally valid. The word struct here just explicitly states that next is a pointer to a structure type named charlistrecord.
It's a reminiscence from C, and you might as well omit the keyword in C++, but if you want to use it, you can.
It's perfectly valid, and it can even be useful if your struct's name is shadowed by a variable, like here:
struct C {};
int C = 0;
int a;
void foo() {
C *a; // multiplies int C by int a
struct C *a; //defines 'a' as pointer to struct C
}
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;
}
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.