Ive been programming in java for about a year and im starting to learn c++ and i tryed
public Unit Human = new Human();
that just came up with a bunch of errors in c++ so i read some tutorials and changed it to
Unit* Human = new Unit();
now i get a error C2228: left of '.getHealth' must have class/struct/union even thou Human is a Unit is a class. am i missing something?

#include <iostream>
#include "Unit.cpp"

using namespace std;

int main ()
{
	Unit* Human = new Unit();
	int i = Human.getHealth;
	cout << i << endl;
	cout << "succsess" << endl;
  return 0;
};
class Unit 
{
  private:
	int Health;
  public:
    Unit ();
    Unit (int);
    int getHealth (){return Health;}
	
};

Unit::Unit ()
{
	Health = 0;
}
Unit::Unit (int UnitHealth)
{
	Health = UnitHealth;
}

Unit.cpp just includes Unit.h

for pointers you access the class members using '->'

hence the line should be

int i = Human->getHealth();

see the error carefully

left of '.getHealth' must have class/struct/union

if its a class/struct/union you can use '.'

1. Member function call in C (in Java too?):

... classvar.getHealth() // not classvar.getHealth;

2. Human is a pointer to a class, not a class var, so

int i = Human->getHealth();

3. Don't include .cpp files. Place Unit class declaration only in unit.h file. Place Unit class implementation (member function definitions) in unit.cpp file:

// File unit.h:
class Unit
{
   ...
};

// File unit.cpp:
... other includes, using namespace etc...
#include "unit.h"
Unit:Unit(): Health(0)
{}
Unit::Unit(int UnitHealt): Health(UnitHealt)
{}

// File with main function:
... other includes, using namespace etc...
#include "unit.h"

int main()
{
   ...
}

Apropos, good news for the former Java programmer - no need in C++ to create Unit instance in Java style, keep it simpler:

int main()
{
    Unit human;
    int h = human.getHealth();
    // and so on ...
    return 0;
}
This article has been dead for over six months. Start a new discussion instead.