object class

Hello,

I'm learning about classe's right know, and I see that a class can have an object itself, for example

1
2
3
  class Class_name {
    //todo
  }name;


In this example the object class is `name`. But what happens is the class has a constructor, in this case is useful to use object clasess? Until now the only way that i see to use its declare it with null values depends the type of the attribute.
it looks like "name" is just a variable declaration of type "Class_name".

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>

using namespace std;

struct test {
	int i;
}ptest;

int main() {
	ptest.i=3;
	cout << ptest.i;
}
}NAME;
is left over from C structs, and IMHO an ugly thing to do. Depending on where it happens, it can produce a global variable, or otherwise make a variable that is hard for readers to locate, etc.

I may be in the minority here but I strongly recommend against this style.
Last edited on
I don't think you're in the minority jonnin; it's quite an unnecessary syntax for 99.9% of cases.

Just to be clear:
1
2
3
class Foo {
    // ...
} name;

is equivalent to:
1
2
3
4
class Foo {
    // ...
};
Foo name;


I suppose one use for it would be to create an anonymous class:
1
2
3
4
5
6
7
#include <iostream>

int main()
{
    struct {int x; int y;} point {4, 3};
    std::cout << point.x << ' ' << point.y << '\n';
}

Last edited on
In this example the object class is `name`
No. The class (aka type) of the object is Class_name. "name" is the name of the object. It's just like:
int i;
Here int is the type of the variable and i is the variable's name.

But what happens [if] the class has a constructor, in this case is useful to use object clasess? Until now the only way that i see to use its declare it with null values depends the type of the attribute.

For the default constructor, it's pretty common to set the values to zeros or nulls, but a class can have multiple constructors and some can take parameters, in which case some of the values might be set from the parameters. A very common case is the "copy constructor" i.e.:
1
2
3
4
5
class Foo {
public:
    Foo(const Foo &);
    ....
};

The copy constructor says "make the new object a copy of an existing one." In that case, the constructor sets the members variables based on the copied object.
Topic archived. No new replies allowed.