C ++ Static variable and unresolved external error

advertisements

I was hoping I could get some clarification on static variables of a class.

For example: I have two different classes which perform completely different functions, alpha and beta. Within alpha, I declare a static variable of type beta so it looks like this:

//alpha.h

#pragma once
#include <iostream>
#include "beta.h"

class alpha{
public:
    alpha(){

    }

    static beta var; 

    void func(){
        var.setX(3);
    }

    void output(){

    }
};

//beta.h

#pragma once
#include <iostream>
using namespace std; 

class beta{

public: 

    int x;
    char y; 

    beta(){
        x = 0;
        y = ' ';
    }

    void setX(int _X){
        x = _X;
    }

};

//main.cpp

#include <iostream>
#include <iomanip>
#include "alpha.h"
using namespace std; 

int main(){
    alpha x, y, z;
    x.func();
}

Now when I try to compile this, I get an unresolved externals error:

error LNK2001: unresolved external symbol "public: static class beta alpha::var" ([email protected]@@[email protected]@A)

I'm not sure what to change or what else I need to add to make something like this work. I want x, y, and z to essentially share the same beta variable. I think I can accomplish this same thing by just passing by reference one beta variable into each of them. But I want to know if it's possible to do this same thing using the static keyword here because static members of a class have the same value in any instance of a class. Unless I have that definition wrong.


static variables inside a class must still be defined somewhere, just like methods:

Put this in main.cpp:

beta alpha::var;