Consider this link. See this code:
class MyClass
{
public:
MyClass();
~MyClass();
private:
int _a;
};
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
We can declare constructor out of the class.
Why can I declare constructor out of the class and why we should do this?
You cannot declare constructor out of the class. You are talking about constructor definition.
class MyClass
{
public:
MyClass(); // declaration
};
MyClass::MyClass() // definition
{
}
You should read this.
The main reason why you should define your constructor outside the class is for readability. It is clearer to declare your class in the Header file and define it in the source file. You can apply this rule any members of your class.
A little quote from the standard :
12.1 Constructors
struct S {
S(); // declares the constructor
};
S::S() { } // defines the constructor
You cannot. This is the constructor declaration, which has to be in the class definition:
// MyClass definition, possibly in .h file
class MyClass
{
public:
MyClass(); // default constructor declaration
...
};
and this is the constructor's definition
// MyClass default constructor definition, possibly in .cpp file
MyClass::MyClass() { }
What you are referring to is the constructor's definition. You can define it outside of the class definition to allow you to de-couple one from the other. Usually this means you put the class definition in a header file, to be included by client code, and the constructor definition (as well as other class member function definitions) in an implementation file that gets compiled. This way, users of your code have no compile time dependency on said definitions.
The main reason for defining the constructor (or any member function) outside of the class declaration is so that you can have a header file and an implementation file. This makes your code clearer to read and allows you to distrbute the interface to your class (the header file) without providing the implementation details.
You can not declare a constructor or anything part of the class, outside it, but you can define
It's a common c++ programming practise of using 2 files for 1 class
For example,
ClassG.h
class ClassG
{
public:
ClassG();
~ClassG();
void anyfunc(int anyarg);
private:
int anydata;
};
ClassG.cpp
#include"ClassG.h"
ClassG::ClassG()
{
//something
}
ClassG::~ClassG()
{
//something
}
void ClassG::anyfunc(int anyarg)
{
//something
}
General Syntax
While declaring, inside .h file type returntype methodname(args_if_any);
While defining in a .cpp file type returntype ClassName::methodname(args_if_any){}
First of all, you have your terminology confused, you need to read What is the difference between a definition and a declaration?. You can not declare a constructor outside of a class but you can define it outside of a class.
So on to the questions as you meant them:
Why can I define a constructor out of the class
Basically the standard has this to say about member functions in section 9.3.2:
A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
So the standard says this is ok, next question:
why we should do this?
It makes your code cleaner and easier to digest, you can separate your declarations into header files and your implementation into source files. This previous thread Why have header files and .cpp files in C++? goes into this topic in more detail.
Yes, you can define the constructor inside the class no matter that whether you are
using .h file or .cpp file. Actually the main difference between both the file is,
header file never compile it only use for checking syntax during compilation of .cpp
file.
Method that you define inside the class by default inline function. If you define one
constructor inside the class it's fine but, if you required to define more than one
constructor then 2 problem occur
Problem 1:
As we know that, when you call inline function it will paste code in called
function that increase the code size and required more memory.
Problem 2:
Reduce the readability of code.
Related
What I am trying to do:
// in foo.hpp
class foo {
private:
int m_a;
long m_b;
public:
foo(); // default constructor (defined in foo.cpp)
template<class T>
int Func1(int a, int b) {
// Func1 definition
// uses member variables m_a, m_b
}
}
// in foo.cpp
#include "foo.hpp"
foo::foo() {
// Foo constructor
// Uses member variables m_a, m_b
}
I understand templates in C++ work as a pattern and are instantiated on demand. Therefore, for the compiler to understand whats happening, the template method definition needs to be in the header file (or else I need to use the other workarounds like using an implementation file (.tpp) and including it in foo.hpp)
This also applies to a template class with non-template methods. The non-template methods need to be defined in the header file.
My question is Foo is a regular class and has one template method and a regular constructor. Should the constructor be defined in the header file or can it be defined in a separate source file?
I ran into this issue at work. Moving the constructor definition to the header file seems to fix the issue.
It would be helpful if someone could provide an explanation for this behavior.
Should the constructor be defined in the header file or can it be defined in a separate source file?
As long as the constructor and the class itself is not a template, you can define it wherever you would like.
One point I would like to clarify: A templates definition simply needs to be visible at the point of instantiation. This does not actually mean that a template must always be defined in a header; it can just as easily be defined in the source file, if its only uses are meant to be internalized within the source file (e.g. it's a private function, only used internally).
Often this does mean that it should be in a header for cases where it's either a public function template, or a class template -- but there are exceptions to this rule.
I have public member functions which are calling private member function. I want to limit the scope of the private member function within the file where definition of private member function is available. In C, I used static before the function name to limit its scope within the file, how do I achieve it in C++.
class Base
{
public:
void XYZ1(void);
void XYZ2(void);
private:
void fun(void);
};
void Base::XYZ1(void)
{
fun();
}
void Base::fun(void)
{
// do something;
}
Now if the member function XYZ2 is defined in some other .cpp file , it should not be allowed to call fun() from it. Basically restrict the fun() function to file scope.
In a1.cpp
void Base::XYZ2(void)
{
fun();// this should result in some error saying fun() is not defined in its scope.
}
I want to limit the scope of the private member function within the file where definition of private member function is available.
A private member function cannot be used by another class or function unless they are granted friend-ship by the class. In that sense, the scope in which the function can be called is already limited.
Having said that, any member function of the class or any class or function that has been granted friend-ship by the class will be able to call the private member function.
The only way to prevent that function from being called outside the file in which it is defined is to make it a non-member static function in the .cpp file. or put it in an anonymous namespace in the .cpp file.
Now if the member function XYZ2 is defined in some other .cpp file ,
it should not be allowed to call fun() from it. Basically restrict the
fun() function to file scope. In a1.cpp
You can put the function in an anonymous namespace (in the cpp file where used). The linkage will become internal, and the name won't be available for access from any other file. One can get the same effect when making the function static (in the cpp file).
If you need to access internal/private members, you could use a nested class who's implementation is defined in the associated cpp file:
//h
class Nesting
{
//...
private:
struct MyPrivateFunctions;
};
//cpp
struct Nesting::MyPrivateFunctions
{
static void f1(Nesting& this);
static void f2(Nesting& this);
//etc...
};
I've passed Nesting as parameter that MyPrivateFunctions may access its private members (since it is nested, this is permitted).
Note that this is very similar to the Impl trick mentioned elsewhere, but it also allows independent member function definitions in other units, and it does not need instantiation.
Most people are suggesting you to use anonymous namespace in C++. But, this would only be feasible if you wanted to do something like, declaring a global variable/function which is supposed to be used strictly inside the file under which it is defined.
We cannot use namespace within the class as per C++ standards, for which you may want to take a look at this discussion: Why can't we declare a namespace within a class?
I used static before the function name to limit its scope within the file.
This worked for you but the understanding here is wrong as static was never intended to be used as scope specifier, its a storage specifier and its lifetime is throughout the program life. You can still access the static variable from other files in several ways, however the compiler here does not provide an externally visible linker symbol and thus cannot be accessed by other translation units / files.
As per the public member functions are concerned they should be allowed to use this private function from whichever file it is defined in. So that the relation between the class member functions are not destroyed. I suppose you would now stop treating static as scope specifier :)
Or you can use the good old Impl- trick if you do not want to show the "hidden" functions of a class to the outside. Private functions are still listed in the header file, after all.
// Foo.h
class FooImpl; // forward declearation
class Foo
{
FooImpl *m_pImpl;
public:
Foo(); // Default constructor (and any other) create instance of FooImpl.
~Foo();
};
// Foo.cpp
class FooImpl
{
// members of hidden types, secrets, methods, ... anything you do not want to show to users of class Foo.
};
Foo::Foo() : m_pImpl(new FooImpl()) {}
Foo::~Foo()
{
delete m_pImpl; m_pImpl = nullptr;
}
As can be seen, with the impl trick you cannot only hide functions, but also data members of a class and type dependencies which would be incurred if the members were part of Foo class.
A way to solve this problem is by using a so called 'facade'. Basically, you have two classes: The first class has the private method which you want to hide, where as the second class implements a wrapper which just provides the methods you want to be accessible. The second class wraps an instance of the first. That's how the whole trick works.
https://en.wikipedia.org/wiki/Facade_pattern
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new in c++.
I'm required to define member functions. I am more familiar with java. I actually confused by the term "member function".
Do we have to define it in the header .h file or the .cpp file?
I am confused by the term of member function
Everything that belongs to a class or a struct is called a member of that class. Hence, we can have member functions. Below is a little exmaple:
class MyClass
{
public:
MyClass();
void myFunction();
int number;
}
Here you have myFucntion() and number members of MyClass
Do we have to define it in the header .h file or the .cpp file?
In C++, it doesn't matter where you define or declare a function or a class.
But keep in mind that putting declaring classes in .h files is better. It will lead to faster compilations of your project. So you should have something like:
// myClass.h
class MyClass
{
public:
MyClass();
void myFunction();
int number;
}
// myClass.cpp
myClass::myClass()
{
// this is a constructor
number = 10;
}
void myClass::myFunction()
{
// this is my function
cout << number;
}
Every function in C++ is a member
Member of a namespace. These are sometimes called "global functions", although that termis not completely correct. They consist of all functions in the global namespace and any functions in user defined namespaces, hence they are called namespace-scope functions.
Member of a class. These are called member functions (even though they are not the only functions that are members!). They can be further separated by non-static member functions and static member functions (I take it you know the difference of this from Java).
Alternate syntax:
class MyClass{
public:
void MyFunction(void); // prototype
}
MyClass::MyFunction(void){ // actual function
// code goes here
}
Think of member function as a method.
In Java, your method (member function) within a class might look something like:
public class MyClass {
public void MyMethod() {
// do stuff
}
}
This is very much the same in C++:
class MyClass
{
public:
void MyMethod();
}
As far as how I've been taught, you declare your class and its members in a header file (.h) and then define them in a .cpp file. You don't have to do it that way and can keep everything with your .cpp file. It's just a better practice to separate them.
in C++ does not matter ...
member functions are just functions inside class (or struct)
you can have headers
you can also have body only ...
if you separate headers and bodies into *.h(pp) and *.cpp files
then you can cross referencing more classes to each other
here some examples:
class C1
{
public:
int a,b,c; // some variables
void f0(); // header only
void f1() { c=a+b; }; // inline body only
friend void f2(); // not a member but can have access to class private things
friend void f3(C1 &x); // not a member but can have access to class private things
};
void C1::f0() { c=a+b; } // body(C1 member) ... can be in separate file
void f2() { C1 c1; c1.c=c1.a+c1.b; } // just function not a member
void f3(C1 &x) { x.c=x.a+x.b; } // just function not a member
if your not member function are accesing only public parts of class then they do not need to be friend.
also there are some restrictions for inline bodies on some compilers
like you can not use asm {} for example...
First, your question "Do we have to define it in the header .h file or the .cpp file?"
You can define (write code for) member functions in either, with different implications.
Any function defined in a header file needs to be an inline function (because it will be included to many .cpp files, and being inline means, this is ok). Luckily, if you combine declaration and definition and do it inside class {...}, they are automatically considered inline, so it "just works".
If you define the member function in a .cpp file, then you need to have the declaration inside class {...}. And if you want to use the class from many .cpp files, then it should go to a .h file, but it can also be earlier in the same .cpp file.
More explanation:
Member function is same as method. Also, for the purposes of this answer, function overloads (same name but different arguments, return value is not considered) are different functions.
In C++ there is separate declaration and definition, though they can be rolled into one. Any function is declared by having just ; instead of function body { /* ...code... */ }. If this declaration is inside a class {...} or struct {...}, then it's a member function. A function call is ok in code as long as there's declaration before the call. Then later on linker will complain if there's no actual function definition, that is a block of code to call. There can be any number of declarations for a function, but only one definition (except for inline functions, where compiler and linker assume duplicate definitions are all the same, so they better be or funny things can happen).
About .h and .cpp files: C++ (and C), .h files are eseentially copy-pasted to the .cpp file during compilation. You could remove the #include and copy paste the contents, and it would be exactly same thing for compiler. But from practical standpoint, definitions go to a .h file, and then they are included in may .cpp files, and because they are declarations, it's ok to have them as many times as you like. But actual definitions go to .cpp files, so they get compiled exactly once, so linker is happy.
Finally a bit about inline functions. If you have a member function definition inside class {...}, it is automatically considered to be inline. You include the same .h file with these inline definitions to many .cpp files, but it is ok because they are by default marked inline (and also, since the code is in same .h file, all definitions should be the same, unless you use some #ifdef preprocessor stuff wrong).
Example:
myclass.h
class MyClass {
void memberFunc1() {
// here is function declaration and definition combined,
// by default inline, so can be include to many .cpp
}
void memberFunc2(); // here's just declaration
}
myclass.cpp
MyClass::memberFunc2() {
// defintion of member function, not inline, must exist exactly once
}
I am working on a codebase that is not my own, that has the following layout:
object.h:
// Objects are defined
// #include "tickets.h" (functions to access the objects)
// An access-handler object is defined
I want to introduce a class that knows about the objects, can be accessed from functions in tickets.h, but can also use the access-handler object. The functions are separate, i.e. class functions that are called in tickets.h do not use the access-handler (I wouldn't know where to start if that weren't the case).
Therefore my class needs to be defined before tickets.h, but some of its functions need to be defined after the access-handler. Is there a way to do this without splitting it up into two header files something like the following:
// Objects are defined
// -- include declaration of class, and definition of functions that tickets.h needs
// #include "tickets.h"
// An access-handler object is defined
// -- include functions of class that need the access-handler
This seems very messy splitting things up like this into two separate files, I was hoping to keep everything contained.
Thanks for any help, I clearly only have a very rudimentary understanding of declarations/definitions in c++.
EDIT: If I use forward declaration and include it before tickets.h (with the class declared in mynewclass.h and functions defined in mynewclass.cc) will mynewclass.cc be able to use objects declared after the inclusion of mynewclass.h? Namely the access-handler object.
EDIT2: Something like this:
object.h:
class obj { // definition }
#include "tickets.h"
class obj_handler {
public void handle { // code }
}
tickets.h:
void do_something(obj o){
communicator.foo();
}
My object (communicator):
class communicator {
public:
void foo() { // code }
void bar() { // use handle() from obj_handler }
}
As you can see, my communicator needs to be used in tickets.h, but can't be defined until after obj_handler. So where should I include it?
If I correctly understand your question - you can use forward declaration to solve this problem. This will allow you to declare some class before defining it's methods. For example:
// this is forward declaration of class A, no definition provided
class A;
class B
{
// uses A
A * a_;
};
// class A definition
class A
{
// may use class B now
B * b_;
};
I'm not quite sure whether I understand this right and don't have enough reputation here yet to make this a comment, so let me try to answer your question this way, please feel free to follow up if I'm guessing wrong:
I believe what you are referring to is an entire class definition, i.e., one including all function definitions within the class declaration. Other than that, it is not very common to see object definitions followed by preprocessor directives. What is typical though is a forward declaration of functions and a class prototype.
So, for example, you could declare in some header.h:
class C
{
public:
void method1(void);
int method2(void);
};
And in some implementation.cpp the definition of the functions like:
void C::method1(void) { /*...*/ }
In the other file preceded in the inclusion chain by your access-handler you then define the other function:
int C::method2(void) { /*...*/ }
What do you mean by access-handler, by the way?
Oh, and your linker likely will yell somewhat at you if you do function definition in a header file.
With regard to your addenda: everywhere you put a forward declaration, loosely speaking, the compiler will insert a copy of the declaration in question, consider it a soft link in the context of file systems. There are negative implications associated with it, like increased duration and the memory load of compilation if you have many forward declarations of the function signature or class. It's impossible to tell whether this will word in your particular situation since only you know the actual code in question. But most likely it would work.
Take a look at these pages:
http://en.wikipedia.org/wiki/Forward_declaration
When can I use a forward declaration?
It is possible to declare a class without defining it (forward declaration) as long as it is defined later on within the translation unit. In the case of functions, one can declare a function without defining it within the translation unit, and the linker will link it to its definition in a different translation unit. Is it possible to do the same with class declarations?
(if this is not possible, is there any use to a forwardly declared class without a definition in the current TL, or is that always an error?)
something like this, except this doesn't compile:
mymain.cpp:
class myclass; // declare without defining
myclass::myclass();
void myclass::barf();
int main() {
myclass *m = new myclass();
m->barf();
return 0;
}
myclass.cpp:
#include <iostream>
class myclass { // define the implementation
public:
myclass();
void barf();
};
myclass::myclass() { } //empty constructor
void myclass::barf() {
std::cout << "barfing\n";
}
It is possible to forward-declare a class, but only pointers and references to forward-declared classes can be used. You can't use an actual object of a forward-declared class because the compiler doesn't know enough about it; in particular it doesn't know how large the object is or what its members are. Trying to forward-declare member functions (as you have done) won't work because the syntax of the forward declaration doesn't allow you to specify whether the functions are virtual or non-virtual (or perhaps inherited from some base class).
It is not often useful to forward-declare a class in a source file, but it can be useful in a header file. In particular it's common to forward-declare a class in a library's public header file and use pointers to that type as opaque handles. The class definition remains private to the library but user code can pass around pointers to objects of that class without ever knowing what the class's implementation looks like. This works particularly well when the pointers are smart pointers.
You can, but only if you use exclusively pointers or references to that class. But you can't use code referring to that class' members (variables or methods). You can only use it to declare pointer variables to that class.
I would suggest you create a myclass.h header file with myclass' full declaration, and include that header in mymain.cpp.
You can only do that through hacks.
The declare before use rule doesn't hold within a class (see here).
Otherwise you can do that by declaring your function as a template function, whose template parameter is of myclass (in your example).
The only non-hack way is to define the class (ie. by including the header file its defined in).