error: ‘g’ does not name a type

Hello. I want to create a class and set some values. Unfortunately this code gives me error that is stated in the title.
1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
  int main ()
  {
  return 0;
  }
  class fall
  {
    public:
     double g, m , t, v, x, w;
     g = 9.81;
  };
you can't do that here.
you have to assign the value in the constructor function.

fall::fall()
{
g = 9.81;
}

or you can make it a constant.

const double g = 9.81;

a class is a variable type. It does not execute code directly inside the definition. All code has to be in one of the member functions.

Last edited on
jonnin is correct. This should help you in the right direction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

using namespace std;

class fall
{
public:

	fall();//defalt constructor
	fall(double, double, double, double, double);//overloaded constructor


	double get_g()//getfunction for g
	{
		return g;
	}
private:
	double m, t, v, x, w;//variables
	const double g = 9.81;
};

fall::fall()//defualt constructor
{
	m = 0;
	t = 0;
	v = 0;
	x = 0;
	w = 0;
}

fall::fall(double m, double t, double v, double x, double w)//overloaded constructor
{
	this->m = m;
	this->t = t;
	this->v = v;
	this->x = x;
	this->w = w;
}

int main()
{
	fall object1;//create object1

	cout << "G: " << object1.get_g() << endl;//just shows that it works

	return 0;
}
Thank you @jonnin and @joe864864. But it seems too confusing :/. I need to study constructors.
Topic archived. No new replies allowed.