Vinod Kambale
Vinod Kambale

Reputation: 11

C++ new operator is giving error

In the below code the statement " s= new int[50];" is giving error.

Error: Error 1 error LNK2001: unresolved external symbol "private: static int * Instack::s" (?s@Instack@@0PAHA) Stack.obj stack_pr

Error 2 error LNK2001: unresolved external symbol "private: static int Instack::top1" (?top1@Instack@@0HA) Stack.obj stack_pr

Error 3 fatal error LNK1120: 2 unresolved externals C:\Users\vinoda.kamble.LGE\Desktop\Bill\New folder\stack_pr\Debug\stack_pr.exe stack_pr

#include<iostream>
#include<stdlib.h>

#define maxma 50;
using namespace std;

class Instack{

private: 
static int *s;
static int top1;

public:

Instack ()
{
    s= new int[50];
}

void Instack:: push(int t)
{
    s[top1++]= t;

}


int Instack::pop()
{
    int t;
t= s[--top1];
return t;
}
};



void main ()
{
    Instack S1,S2;

S1.push(522);

S2.push(255);


cout<<"S1 pop",S1.pop();

cout<<"S2 pop",S2.pop();

}

Upvotes: 1

Views: 78

Answers (1)

Pradhan
Pradhan

Reputation: 16777

The reason is that static class members need to a definition. Adding something like this outside your class definition will solve your linking troubles.

int* Instack::s = nullptr;
int Instack::top;

Unfortunately, that leaks memory. What you likely meant to do is have both s and top as non-static member variables.

Upvotes: 1

Related Questions