C++ Inheritance Problems

Soldato
Joined
7 Apr 2004
Posts
4,212
Hi,

Im trying to get some basic C++ inheritance working across 2 header files, and its been a while since ive used C++, so its probably something really silly :(

Header 1: serv.h
Code:
#include <iostream>
#include <vector>

using namespace std;

struct server_data
{
	string server_name;	
	string host_name;	
	int port;	
	string user_name;	
	string password;	
	bool require_authentication;
	int max_connections; 

	int priority;

	bool operator < (const server_data& a) const
	{
		return priority < a.priority;
	}
};

class NCServer
{

	public:
		vector<server_data> nc_server;
		int AddServer(server_data sc);
		int RemoveServer(string server_name);

};

Header 2: conn.h
Code:
#include "serv.h"

class NCConnection : public NCServer
{
public:


};

I get a whole host of redefinition errors for things in the first header file :confused:

Any ideas what I have missed out / doing wrong?

Thanks

Jack
 
nothing wrong with these files as they are at the moment

do you have any other code that may be causing the problem?
 
Let me guess, in your .cpp file, you're doing this:

#include "serv.h"
#include "conn.h"

Am I right?

You need to put header guards in your .cpp files (or if you're using Visual Studio and are sure you'll never use any other compiler, #pragma once). You do this like so:

Code:
in serv.h...

#ifndef SERV_H_
#define SERV_H_

// ... code

#endif

in conn.h

#ifndef CONN_H_
#define CONN_H_

// ... code

#endif

You should put that #ifndef on the very first line of the .h file, as modern compilers are often designed to spot internal header guards and deal with them quickly.
 
Thanks a lot Mr Jack, the missing header guards fixed the problem.

Also, you mentioned that i shouldn't include namespace std in headers, well as you can see in the header above i have a struct that uses std::string? Is there anyway i can just declare a struct in the header and then implement it in the .cpp? Or is what i have done correct?
 
Just bring the names you need in, rather than the whole std namespace:

using std::vector;
using std::string;

...

vector<int> bla;
string foo;

Or of course you can just qualify things fully:

#include <list>

...

std::list<int> moo;
 
Also, you mentioned that i shouldn't include namespace std in headers, well as you can see in the header above i have a struct that uses std::string? Is there anyway i can just declare a struct in the header and then implement it in the .cpp? Or is what i have done correct?

It's bad programming practice to put using directives in header files, you should use the fully qualified names instead, otherwise your just dumping everything into the global namespace and losing all benefit of namespaces.
 
Back
Top Bottom