How does including libraries work with classes?

Hello, so if I create a class, but I use a headerfile for the declarations, and an additional CPP file for the functions, constructor and deconstructor, how would I implement the libraries that I need to use?


So let's say I want my class to have a string called sPassword, and I want the constructor to use the rand() function to create a string of random numbers/letters and assign it to sPassword, and then print it on the screen whenever an object is created.

How would I include the cstdlib, iostream, and ctime libraries to do this?

I don't think including them in all three files is a good idea, since the book I'm using said C++ doesn't like it.

If I include them in the cpp file for the class functions, and compile the program, will it automatically include it in the main.cpp?

If you have some spare time and can write a sample program, that would be amazing.

tl;dr
Write program with a class called "Account", when an object is created, it automatically creates a string of random numbers (you can do something like int iPassword = rand();) and assigns it to sPassword, and prints it on the screen.

Thank you very much.
So I figured it out. You basically can just write all of the #include commands in the header file, and once you include that in the two cpp files, those libraries get carried over.

In general, only use #include's where you need to use them. And also, do not assume that another included file has already included the headers you directly use.

For example, if your header file declares class A as
class A { A(); };
No header file is needed here.

But in your implementation file, if you need to call rand(), that's where you would be
#include <cstdlib>

Yes, it won't hurt to put #include <cstdlib> in the header file, but you're exposing an unnecessary part of the implementation in doing so.
Last edited on
Topic archived. No new replies allowed.