I have a dummy question for you...
I am trying to access a function from a class (Key) from another class (Music), but it gives the error:

‘thiskey’ was not declared in this scope

So I guess the Key object thiskey is not public for this class.

What I have (stripped down, I left out some loops and a lot of functionality for readability, so I am sorry if the code does not actually do much):

Key thiskey();
int main( int argc, char **argv )
	char keyid='A';
	Key thiskey (keyid);
	Music music1(1);

class Music{
	char keyid;
		int id;
		int music[20];

		Music(int id);
		bool feasible();

Music::Music(int id){
	music[2]=thiskey.display;    //this is the error line

class Key{

	int keylength;
	int keyset[12];

	void display();


Key::Key(char keyid){
        //keyset array is generated here

void Key::display(){
	cout << "\nKey output:";
	cout << keyset[1];
	//for (int i=0; i<keylength; i++){
	//	cout << keyset[i];

Many thanks for any suggestions! Do I need to use a scope? Of do I define this wrong?

Think of a class as an entity all on its own -- the class has no knowledge of anything outside its class. It's not possible for a class to access objects declared elsewhere in the program.

Mmmm... I guess I will have to restructure the program.

Any chance friends/inheritance functions would come in handy here? I am going to have to rethink this...

The code you posted here produces a lot more than one error.
For example:

Music::Music(int id){
	music[2]=thiskey.display;    //this is the error line

You appear to have an extra '}' and you should do 'thiskey.display()' when calling functions. Also, display is a void function so you aren't even assigning anything to music[].
If you look carefully through your code you will find other similar problems.

Side Note: It is generally useful to implement main last last so that you don't have to forward declare your functions.

Edited 6 Years Ago by Valaraukar: n/a


As I mentionned, I seriously stripped down the code. The three pieces are actually seperate files and the extra } got missed in deleting. Sorry for the confusion.

You can use thiskey in the music constructor, but it won't work written as is. If you include a Key thiskey as a parameter in the Music construct, and pass thiskey to the constructor, it'll work.

Also, what was said before,


display is a void, and void doesn't return anything. I know you said you trimmed some code, but what exactly is going to be assigned to music[2]?

This article has been dead for over six months. Start a new discussion instead.