Reputation: 1
I wrote code where I defined a structure outside of main, for a queued linked list for a class. It basically looked like this:
class Queue
{
public:
void enqueue (int x);
void dequeue ();
void print ();
};
struct queueNode
{
int data;
queueNode * next;
queueNode * prev;
};
queueNode * head;
queueNode * tail;
queueNode * n;
//class functions that use head, tail, and n
int main ()
{
//functions that use head, tail, and n
return 0;
}
This is a very, very stripped down version of it, but you get the picture.
Problem is, now that I'm splitting it up into different files, I can't figure out where to put head, tail, or n.
If I put them in the header, they're not bracketed so they can't just be the tail end of the header file.
If I put them in the implementation file, they aren't accessible to main. And I can't #include the implementation file because it's a redefinition.
And if I put them in main, they're not accessible to the implementation file.
Where should I put these? Is there some kind of convention?
Upvotes: 0
Views: 2909
Reputation: 43
If you want to have
queueNode * head;
queueNode * tail;
queueNode * n;
accessible through your main function you would normally either put them inside a header file to be included in the spot you want (as including a header file is simply copy pasting it) or just declare them above your main function in the main.cpp file. simple as that.
like what was said though it's usually best to put the definitions (class/struct and member outlines) inside a header file to include at the top. and flesh out the functions in the source files.
usually when declaring a variable/object you do it right next to where you need it unless there's multiple places it's needed in which case just slapping it into a header with include guards would do the trick. Example:
main.cpp
#include "queue.h"
#pragma once
queueNode * head;
queueNode * tail;
queueNode * n;
//class functions that use head, tail, and n
int main ()
{
//functions that use head, tail, and n
return 0;
}
queue.h
class Queue
{
public:
void enqueue (int x);
void dequeue ();
void print ();
};
struct queueNode
{
int data;
queueNode * next;
queueNode * prev;
};
queue.cpp
#include "queue.h"
//queue and other methods should go here.
just remember that if your compiling multiple source files without an ide you need to link them together.
Upvotes: 0
Reputation: 1479
I would do like that:
The declaration of the class and the structure -> to a header (or separate headers). The node variables are to be put to a source file (c or cpp) to be not accessed from outside directly; if other source files need access to them - you can provide get/set functions for this purpose. Also to the source file should come the implementation of the class' methods if they are not inline.
Upvotes: 1