Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of Declaring a Constructor in Header (.h) and then Defining in a Class File (.cpp) C++ [closed]

Tags:

If anyone could lay this out, I would appreciate it. Example of what I thought would work (assume the needed #include statements are there):

//.h file class someclass(){}  //.cpp someclass::     someclass(){          //implementation          // of           //class }; 
like image 919
user2020058 Avatar asked Jan 29 '13 01:01

user2020058


People also ask

What is the correct syntax of constructor in CPP?

C++ allows us to use the three constructor functions we have discussed in the same class. For example: class complex { int a, b; public: complex() // default constructor { a= 10; b=45; }; complex( int x, int y) // parameterized constructor { a=x; b=y; }; complex( complex & v) // copy constructor { a=v.a; b=v.b; }; };

Can I define constructor in header file?

In both cases the constructor is inline. The only correct way to make it a regular out-of-line function would be to define it in the implementation file, not in the header.

What Is syntax of defining a constructor of class A?

The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it. class A { public: // defining destructor for class ~A() { // statement } }; Destructors will never have any arguments.

What is a constructor write the syntax of declaring the constructor?

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.


1 Answers

someclass.h file

#ifndef SOME_CLASS_H #define SOME_CLASS_H      class someclass { public:   someclass();  // declare default constructor  private:   int member1;  };  #endif 

someclass.cpp

someclass::someclass()   // define default constructor : member1(0)             // initialize class member in member initializers list {    //implementation } 
like image 110
billz Avatar answered Sep 20 '22 06:09

billz