0

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" (?var@alpha@@2Vbeta@@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.

2 Answers 2

5

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

Put this in main.cpp:

beta alpha::var;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry if this seems like a stupid question. Is this considered using a global variable?
No it's not (neither stupid nor global :). Take a look at this link parashift.com/c++-faq-lite/ctors.html#faq-10.12
4

Add this to main.cpp:

beta  alpha::var;

var in h-file is only type declaration. Variable should be created in some source file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.