How to write classes? C ++

Hey, I really don't understand them. I read a tutorial about classes in C ++, and I don't get a few things: In every example and tutorial that I saw, functions are never written inside the class! For example, why write such a class:

#include <iostream> using namespace std; class test { private: int x, y; public: test (int, int); int tester () {return x + y; } }; test::test (int a, int b) { x = a; y = b; } int main() { test atest (3, 2); test atest2 (2, 6); cout << "test1: " << atest.tester() << endl; cout << "test2: " << atest2.tester() << endl; return 0; } 

or like this:

 #include <iostream> using namespace std; class test { private: int x, y; public: void set_values (int,int); int testfunc () {return x + y; } }; void test::set_values (int a, int b) { x = a; y = b; } int main() { test tester; tester.set_values (3, 2); cout << "test1: " << tester.testfunc() << endl; return 0; } 

and not just like that:

 #include <iostream> using namespace std; class test { public: int tester (int x, int y) { return x + y; } }; int main() { test atest; cout << atest.tester(3, 2) << endl; return 0; } 

Honestly, I just don't get it!

Why do we need private members?

When and how should destructors be used?

How do I write my classes?

I am very confused here and I really need someone to clarify everything for me ... thanks

+1
source share
10 answers

The example plausibly separates the setting and extracts the values, because there are more between them than you see in this main function. If this does not happen, you are absolutely right that you should combine them and even exclude the class in favor of a free function.

For example, the code might look something like this:

 void example(Test obj) { if (something) { process(obj.tester()); } } int main() { int x, y; // Imagine these are assigned to user input. Test obj (x, y); example(obj); // Obj.tester may or may not be used. If the x + y was not // separated, then you couldn't "maybe use" it. return 0; } 

Why do we need private members?

Not. They are more documentation than anything else. However, accessibility (public / protected / private) is documentation that is checked by the compiler. This check is useful mainly for encapsulating values, but encapsulating is much more than just noticing something non-public. For example, if you (from a public method) return a reference to a non-public data element, you have associated the implementation of this element with the public interface of the class.

When and how should destructors be used?

If you need special logic of destruction. Read about Rule Three . Write them as if they were a class method with the name "~" plus the class name, without parameters and omitting the return type (even invalid), similarly for ctors.

How do I write my classes?

You do not need to define methods outside the class. In fact, implement all the methods inside the class to start with it, and then move the methods as necessary. It’s much harder to mess up when you learn the important basics of the language and are much more convenient for the types of classes that you will write initially. Use ctor initializers when they are as possible as assigning them in a ctor package.

 struct Test { Test(int x, int y) // Use the same names rather than inventing 'a' and 'b'. : _x (x), _y (y) {} int tester() const { return _x + _y; } // Move outside the class when needed, if at all -- and it won't be needed // for a function like this. // Because this doesn't modify anything, it suitable to be const, which // means it can be called on a const Test object. int _x, _y; // Technically public, but with a "non-public name". Mark private as you // wish, or as the design settles down. }; 

Note. I used "struct" to declare this class instead of "class". The result is identical, except that I skip the β€œpublic” on any base classes (they are not here, but the databases are more often public than not), and the availability of elements by default is also β€œpublic”: this leads to reduction and a little more clean up the code.

+2
source

As Greg says, you really need to read a book.

How do I usually write my classes?
Classes allow you to combine data and functions that affect them in one thing.

Why do I need personal members?
Access to private members is only possible through functions in your class, this allows you to control how the data is stored in the class if the class user cannot do what you do not expect.

When and how should destructors be used?
When you have something to clear, when you try to object, it is no longer needed, the file is closed or the memory is freed.

+3
source

Private members hide the insides of the class from manipulation from the outside. This allows the class writer to change the internal implementation details without worrying about breaking another code and allowing the class to ensure that it remains in the correct state. (Consider a triangle with leg lengths as common data elements: there would be no way to prevent any other code from setting the leg length to 2, 3, and 7.)

A destructor should generally free up resources stored in the object β€” things like file descriptors, database connections, and memory blocks on the heap. If an object does not have such resources, you usually do not need to write a destructor. If so, you probably also need to write your own copy constructor and assignment operator. (You can use smart pointers to indicate blocks of memory, and they have their own destructors.)

You should write your classes, indicating what the objects should do. Then record function announcements that allow callers to perform these actions. This gives you the public interface of the class, so these functions should be public: Then write everything you need to implement these functions. This will almost certainly include data and will likely include other functions that will call public functions. These things should be private:

In general, the class definition goes into the header file, and the header file should have as little as possible. A smaller header file means faster overall compilation time (since the header file will be #include d with at least one code file) and reduces what other people, or you six months later, need to read to understand what the class does. Implementations are performed in a code file.

+1
source

Why do we need private members?

Private members allow you to apply class invariants. Say that your class is a bank account, you want to reinforce the idea that you do not have negative money in your account. A class cannot guarantee that if any code there can change the account balance. Make the account balance private, then the class can guarantee that the property takes place.

When and how should destructors be used?

You use destructors to free resources that are stored in the class, sockets, db connections, memory. Something to be aware of is the rule of three. That is, if you have a non-trivial constructor, you will most likely need a destructor and copy constructor.

How do I write my classes?

Common guide lines for writing a class will follow SOLID principles.

+1
source

When you get into the driver's seat of a car, you have certain hopes for how to drive this car. Turning the wheel to the left should bring the car to the left. Depressing the accelerator pedal should speed up its operation, and depressing the brake pedal should slow it down. As a driver, you have the right to make these assumptions because the world has standardized the interface through which you drive.

So what if you drive an electric car instead of a car with an internal combustion engine? Should the wheel and / or pedals be changed? Of course not! It is foolish to change controls only because some technical component of the car is different. It does not matter if the car is powered by gas, electricity, water, hamsters or pure willpower; turning the wheel to the right should make the car right!

When it comes to designing an object, public functions act as an interface for the programmer. A programmer may have general assumptions that certain function calls will produce certain kinds of results. Continuing the analogy with a car, good state functions will be accelerated (), turnWheel (), toggleLights (), etc. A bad public function would be FuelInjection (). Why is the driver interested in working with this particular component? The car must handle these parts! Good private members would be FuelInjection (), exhaust (), etc.

After some time, the analogy of the car breaks down, so consider a more practical example. Say you are making an image class. How do you imagine interacting with a good image object? Like this?

 Image i; i.loadFromFile("myFace.jpg"); 

Or how is it?

 Image i; i.preparePixelBuffer(); memset(i.pixelBuffer, 0, i.pixelBufferSize); FILE* fp = fopen("myFace.jpg", "r"); bool doneLoading = false; while (!doneLoading) ... 

Never use objects / classes "just because". Think of the focused short-term behavior that you want to combine into a class. It will make your life a lot easier!

+1
source

Should I define methods in the class? Why do we need private members?

As Fred said, it is often easier to do when you are studying, playing with code, or even as a professional, like your first project or other circumstances. After a specific fact should be noted, it is that the definitions of the body class are automatically "embedded", which means that the compiler inserts the code into the calling point and can avoid function calls.

The fundamental principle of separation of methods from the body and private members is encapsulation , or communication / cohesion. This means that other code that uses the class is only interested in what it claims (the interface), and not how it does it (implementation). This is useful in two main ways:

  • When writing client code, we can better focus on things that matter.
  • If we need to fix the implementation, we have a good chance not to violate the client code.

Ultimately, it all comes down to trying to solve a problem in software development, how to break large systems into components in order to have a managed code base. C ++ allows you to define interfaces using the public part of the class bodies and implementation as a private section or .cpp file. This reduces the overall connection in the system and, therefore, its overall complexity.

When and how should destructors be used?

An example of the concept of encapulsation are objects of "own" resources. Any resource item that an object creates is also responsible for the release. When an object is destroyed, it needs to free up the remaining resources. Now, often for simple objects you do not need to explain anything. The main case for a new programmer will call "delete" for objects created using "new". It is useful to avoid this using smart pointers such as std :: auto_ptr <>.

How do I write my classes?

Definitely make sure that you understand how to break code into a .cpp file. By doing this, for self-study, you will be fine with the code in the class. You may find that the body of the class becomes long and difficult to navigate. This is a sign that now is the time to divide it. Another good case for splitting is when an "interesting" implementation. Suppose you have a drawing class that is implemented using OpenGl. Entering data in a .cpp file means that the rest of your code does not end, including OpenGl header files.

+1
source

Traditionally, methods defined inside a class definition are built-in. That is, the call is not made when they are executed. However, with newer compilers, inlining rules are more complex. However, I think that a good rule of thumb should still define the methods in the header that you would like to use.

You do not need private members. Classes provide a way to organize your code into a logical unit. By making private members, you encapsulate this logic in your class. The advantage is that you can focus on these private members without worrying about what the other parts of your application do, because no other part of the application will directly access these members.

0
source

The first writing style, as shown above, allows you to separate function definitions (your class interface) into a header file and function declarations (class implementation) into a .cpp file. You can learn more about header files in this question . There are advantages to embedding in some methods, and one way to do this is to write function declarations in the class, but in order to get these benefits, the method must meet several criteria.

Private members allow you to hide the data of your class so that only this class can manipulate this data. It provides a way to handle proper encapsulation and the important concept of object-oriented programming. Encapsulation binds all the methods that work with some part of the data into one class, which, perhaps, helps to create nice and understandable projects in software.

More about this destructor in this question . If you are confused about a C ++ destructor, you can read it in memory in C ++ in a good C ++ book like Accelerated C ++.

0
source

You really need to learn something else! let's start with the participants a private member means that you can access it, read it, change it in any way only with the class a protected member means the same thing, but you can also access it through inheritance (inherit from later) public funds ... well, that you can access it from anyone you want. In small programs, this does not matter, but if you are in a team with 10 or 100 programmers, you probably want some things to stay as they are and not be able to change everything you want.

written like that because it's a C ++ way. The truth is that the part where you define your class is β†’ class square {}; this is a class definition. you design your class and define the members of the class. and then after the compiler knows which member belongs to the class, then it goes to the actual move and uses the actual members, you will better understand if you use the .h files in your program the header where you create your collision, and then on cpp, which includes .h, you actually implement the methods and values ​​of the variables

and the best part is destructors. Destructors require the removal of objects when an instance of a class is deleted. Removing objects is part of programming that requires a good foundation for allocating and freeing memory. I have to offer a book that the book helped me a lot: "Thinking in C ++" is my advice, continue coding, no matter what! if you get a stack for something try to find examples, if you still cannot solve the problem, take a break and try again later

Enjoy it!

0
source

Many say that you need to split your class into a .h file and a .cpp file. This is usually done by hobby programmers because it helps make huge classes much smaller to negotiate when you look back at them to see what they are doing. Having all the code that makes this class work in the same file as all the functions / data elements that you can use, it is very difficult to understand how you can actually use this class.

In fact, it allows you to simply look at the header file after it is completed and forget how the class really works under the hood! At least that goal. When you get into professional programming or just really big projects, it also helps with compilation times, separating how it works from people who code with you, who don't need to worry about it, etc.

Private members should basically protect your future from their past. So ... let's say you write a class that has a method that returns how much money an employee has.

 int Employee::GetDollars(int employee_id); 

you call it. All this returns a private int int [] 'data variable in the class, possibly in the lines "return dollars [employee_id]"; Now in the future, if you change the way you find out which employee_id that employee or something else gets, you should change it in only one place. Instead of just using classname.dollars [id], because then you will have to change it at every single point in your program that you have ever used!

0
source

All Articles