Monday, July 25, 2016

Digest for comp.lang.c++@googlegroups.com - 25 updates in 7 topics

tokauf@gmail.com: Jul 25 09:40AM -0700

Hi everybody,
 
I have a little class hierachy:
 
|Base|
|
|Sub|
/ \
|Sub2| |Sub3|
 
Here's my main-code:
 
1 #include "Sub2.h"
2 //#include "Sub3.h"
3
4
5 int main () {
6
7 Sub sub("thomas", 53);
8 cout << sub.getMsg() << endl;
9
10 Sub2 sub2 ("Thomas", 53, "Deutschland");
11 cout << sub2.getMsg() << endl;
12
13 //Sub3 sub3 ("Thomas", 53, "Deutschland", "Male");
14 //cout << sub3.getMsg() << endl;
15
16 return EXIT_SUCCESS;
17 }
 
 
This works fine. But when I include Sub3.h and delete the comments from Sub3 sub3 then I get errors:
 
In file included from Sub.h:1:0,
from Sub3.h:1,
from main.cpp:2:
Base.h:3:7: error: redefinition of 'class Base'
class Base {
^
In file included from Sub.h:1:0,
from Sub2.h:1,
from main.cpp:1:
Base.h:3:7: error: previous definition of 'class Base'
class Base {
^
In file included from Sub3.h:1:0,
from main.cpp:2:
Sub.h:4:7: error: redefinition of 'class Sub'
class Sub : public Base {
^
In file included from Sub2.h:1:0,
from main.cpp:1:
Sub.h:4:7: error: previous definition of 'class Sub'
class Sub : public Base {
Paavo Helde <myfirstname@osa.pri.ee>: Jul 25 09:12PM +0300

> from main.cpp:1:
> Sub.h:4:7: error: previous definition of 'class Sub'
> class Sub : public Base {
 
You need to protect your header files against multiple inclusion.
Nowadays in practice it is just OK to put in the start of each header file:
 
#pragma once
red floyd <no.spam@its.invalid>: Jul 25 11:12AM -0700

> / \
> |Sub2| |Sub3|
 
> Here's my main-code:
 
[redacted]
 
Search google for "Include Guards". Learn them. Use them.
 
Also, if you are going to post sample code, you need to include
your headers.
tokauf@gmail.com: Jul 25 12:01PM -0700

> from main.cpp:1:
> Sub.h:4:7: error: previous definition of 'class Sub'
> class Sub : public Base {
 
 
Oh my god. I know this rule and I forget it;-). Thank you.
Jerry Stuckle <jstucklex@attglobal.net>: Jul 25 03:14PM -0400

On 7/25/2016 2:12 PM, Paavo Helde wrote:
 
> You need to protect your header files against multiple inclusion.
> Nowadays in practice it is just OK to put in the start of each header file:
 
> #pragma once
 
Just beware that not all compilers support #pragma once. However, all
standards compliant compilers support include guards, i.e.
 
#ifndef __SUB3_H_INCLUDED
#define __SUB3_H_INCLUDED
.... file goes here

No comments: