Sa'ed Abdelhafez Sa'ed Abdelhafez - 2 months ago 6
C++ Question

pointer after a class

What should I add in the Ninja constructor to make this code work without editing it? . What dose it mean when I Just set a pointer directly after a class? I saw that once in a code for a game and i couldn't understand that syntax.

//in the main (non Edit):-

Ninja *Saed;
Saed->setAttackPower(100);
cout << Saed->getAttackPower << endl;


//in the Ninja.h :-

#include <stdio.h>
#include "iostream"
#include "string"
#include "Enemy.h"

using namespace std;
#pragma once

class Ninja :public Enemy{

public:
Ninja();
void setNinjaName(string a);
string getNinjaName();
protected:
string ninjaName;
};


//in the Ninja.cpp :-

#include <stdio.h>
#include "iostream"
#include "string"
#include "Enemy.h"
#include "Ninja.h"
using namespace std;
#pragma once

Ninja::Ninja()
{

}

void Ninja::setNinjaName(string a)
{
ninjaName = a ;
}

string Ninja::getNinjaName()
{
return ninjaName;
}


// thank you :)

Answer

The problem is that you have declared an uninitialized pointer and are not pointing it at a valid Ninja object before calling methods on it:

Ninja *Saed;
Saed = new Ninja; // <-- add this!
Saed->setAttackPower(100);
cout << Saed->getAttackPower << endl;

And don't forget to destroy the Ninja object when you are done using it:

delete Saed;
Comments