Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there two files created (.h and .cpp) when creating a new C++ class?

I have programmed a bit of C++ back about 14 years ago. I got acquainted to new technologies such as .NET with which I work mostly work with.

Now, I'm writing a simlpe phone list Windows Application which I want to make it C++ so that I can better view C# and C++ differences.

Let me say that I have already noticed a difference! Hehehe... Hence, one of those difference is that when creating a new C++ class from Visual Studio template, it creates not only the .cpp class file, but also a header file along with it.

Why is that so? Why creating a class1.h and a class1.cpp files for one classe?

I remember that header files are likely libraries of functions and objects, if we may say so, for future reuse, do I remember correctly?

Questions

  1. Why are there two files (.h and .cpp) created when adding a new C++ class?
  2. Should I define the members in the header file and define the functions core in the cpp file?
  3. If no to 2, what is the header file for in this particular scenario?

EDIT #1

Then should my code look like this?

// Customer.h header file
ref class Customer {
    private:
        char* _number, _name;
        long _phoneNumber;

    public:
        char[] get_number();
        void set_number(char* number);
        char[] get_name();
        void set_name(char* name);
        long get_phoneNumber();
        void set_phoneNumber(long phoneNumber);
        void set_name(char* name);
}

Then:

// Customer.cpp
#include <Customer.h>

char[] Customer::get_number() {
    return _number;
}

void Customer::set_number(char* number) {
    if (number != null && sizeof(number) < 1) return;
    _number = number;
}

// And the other members here...

Now I know, there most be plenty of errors in my code. I'll be happy if you help me correct them so that I can improve my C++ skills.

Thanks for helping me figuring it out.

like image 598
Will Marcouiller Avatar asked Feb 25 '23 15:02

Will Marcouiller


1 Answers

Functions and Classes in C++ must be declared before their use, this is simply a declaration saying that these functions can be used from this file. These declarations are imported using header files (.hpp/.h files).

To declare a function, you would write this:

return type function name ( arguments );

So this function:

int factorial (int x)
{
  if (x == 0)
    return 1;
  return x * factorial (x - 1);
}

Would be predeclared like this:

int factorial (int x);

Declaring classes is like this:

class class name { function and variable declarations };

So class Foo with method bar, and public member variable baz would look like this:


foo.hpp:

#ifndef FOO_HPP_
#define FOO_HPP_

class Foo
{
public:
  int baz;

  void bar ();
};

#endif

foo.cpp:

#include "foo.hpp"
#include <iostream>

void Foo::bar ()
{
  std::cout << baz << std::endl;
}
like image 91
Joe D Avatar answered Apr 27 '23 21:04

Joe D