When to dynamically allocate objects?

Hi! I am new to this forum and to C++ programming, which I fell in love with :). My question is....In software development, when do you need to create dynamic objects? I know how to use dynamic allocation in general, but I can't seem to decide when and why to use it.

Thank you!

If you can't decide at compile time
- how many of a thing you need
- how to fully construct a thing
Then dynamic allocation is the way to go.

For (a bad) example, if you're reading in a list of words from a file.

This would be very restrictive, 100 words with a maximum length of 9 chars.
chars words[100][10];

At least now you can choose the length of the words, even if you're stuck with 100 of them.
char *words[100];

Now you're fully flexible in both the number of words, and the lengths of words.
char **words;

Of course in C++, this would just be std::vector<std::string> words; and you no longer have to worry about any dynamic allocation in your own code. The standard containers would dynamically allocate on your behalf.

If you use all the features that C++ offers, you shouldn't need to do 'new object;' explicitly yourself that often.


oh I see now. Thank you for the advice. One more question: if I want to make an array of customers and for example change it every time a new costumer is added should I use an array or smth from libraries?

Do you have any recommendations(links, articles...) for me to read about these topics?

Tnk u very much.
Last edited on
You'll need a few decent books.
https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282

As for your more immediate question, the thing to be using is std::vector.
https://en.cppreference.com/w/cpp/container

There's also http://www.cplusplus.com/reference/stl/, but the cppreference one seems to do a much better job of keeping up with C++14/17/20 developments.
in c++, you avoid this if you can.
prefer to use a vector or list or other container that does it for you.

my answer usually comes down to this:
if you need extreme performance AND you can SHOW in a PROFILER that DIY is significantly faster than using the libraries, then you may want to consider it. This is an unusual chain of events. It is most frequently seen if you write your own high speed memory manager for your program.

You also need it when forced. Older libraries and interfaces may require it, or if you need some C libraries.

that said, pointers are still awesome. you can use a vector and push back to manage memory for your own tree class, for example. just push a node into the vector and take a pointer to it and proceed as before (with the benefit of being able to iterate the items on the side in the hidden sequential container!).
Last edited on
hi! thx for the reply joanin.
I have done some research but I put a vector in a private field and I am trying to access it using getters and setters.
I read that setters on vectors can cause problems..Then what about encapsulation? I want it as private.
I searched on the internet and tried all the solutions, but nothing seems to work. I still get that error that says the member si not accessible because it is private. And I know that friend functions can access private members..Am I wrong or smth?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Bank.h
#pragma once
#include<iostream>
#include<string>
#include<vector>
#include"Customer.h"
using namespace std;

class Bank {
private:
	int size;
	int customer;
	vector <Customer> customers;
public:
	Bank();
	void add(Customer& customer);
	void setCustomer(vector<Customer> const &cust) {
		customers = cust;
	}
	const vector<Customer> &getCustomer() { return customers; }
	Customer& find(string firstName, string lastName, string account, int ssn);
	friend ostream& operator<<(ostream& ostr, const Bank& bankCustomer);
	friend istream& operator>>(istream& istr, const Bank& bankCustomer);

};

ostream& operator<<(ostream& ostr, const Bank& bankCustomer);

istream& operator>>(istream& istr, const Bank& bankCustomer);



Bank.cpp
#include<iterator>
#include"Bank.h"


ostream& operator <<(ostream& ostr, Bank& bankCustomer) {
	ostr << " [ ";

	//copy up to but not including the last element 
	//putting a ; after each one
	
	copy(begin(bankCustomer.customers), end(bankCustomer.customers) - 1, ostream_iterator<Customer>(ostr, "; "));
}
In the early study of encapsulation, and of private members, the "get/set" pair is an introduction, but you'll find in professional code they do not appear frequently.

Encapsulation is more than merely privacy, but of operation of the internals.

Consider if every private member variable has a simple get and set function. Is the member actually private anymore? If the "set", in particular, allows what amounts to the unrestricted ability to modify the member variable, "privacy" is basically eliminated.

In my view where "get" and "set" are either the only or the primary functions associated with a member variable, it is a hint that perhaps privacy isn't even warranted, but is more generally an indicator that the "set" is being used by functions outside the class for a concept which should be a member function of the class.

Consider:

1
2
3
void setCustomer(vector<Customer> const &cust) {
		customers = cust;
	}


This proposes to copy a vector into customers. I'm not convinced this is a good thing to do.

The class is capable of starting with an empty container of customers, and subsequently accept customer information and append it to that list. "Set" functions don't usually apply to a container member in this fashion, because your proposed "add" function probably does all that is implied.

I note you have no "get" for the "customers" container, which is good because you have a "find" that would do the work likely to be the reason for "getting" that container.

Now this comes to the primary question about the streaming of a bank.

As you've discovered, where "customers" is private, the operator function is denied access to customers.

It is natural for students to react with an impulse to provide access to "customers" for the operator function, but it is an error to think so.

The bank has declared private ownership of "customers", and should be the sole proprietor of it. It is "Bank" that should copy the customers to the stream, and not the operator function.


Last edited on
Why are you declaring two different ostream overloads, one a friend of the class (line 22) the other a non-friend (line 27). Which of these two different "prototypes" do you think you're implementing on line 38? (Hint: It's probably not the friend you seem to think it is.)

Does Customer have an ostream overload as well?


jlb,

You were right. I don't know why I have implemented it twice. I saw it in a tutorial and it seemed to work...
It is my first programme that I am writing and I am making a lot of mistakes :(... Customer doesn't have an ostream overload.

Niccolo,
I am still confused by all this private and getters and setters. Then if u make a variable as private, then why make getters and setters to change it? In the above example if I make the vector as public, everything works fine.

Thx for the answers.
Customer doesn't have an ostream overload

Then what are you trying to do with that copy() call? Do you realize that that third parameter expects you to have an overload of the operator<< for Customer?

By the way did you remove lines 27 and 29?

I did remove them and solved problem.
Here insted of ostream& operator <<(ostream& ostr, Bank& bankCustomer) {..}
I should have written ostream& operator <<(ostream& ostr, const Bank& bankCustomer) {
But I am still confused about all the const thing. I would like to do some research and read about it....but don't know what to search for exactly..
thx
> Why are you declaring two different ostream overloads
those are not different declarations, they are the same
and you can declare things whatever many times you want, there's no issue
the problem is with multiple definitions


@OP: https://isocpp.org/wiki/faq/const-correctness
I read that setters on vectors can cause problems.

Just about anything you do can cause problems if it isn't well thought out. Put less stock in crude generalizations and look at what you want to DO.

things you can do to a private vector member:
you can write your own class.pushback wrapper that calls member.pushback
you can overload [] for the class so that class[x] is {a copy of, a reference of, etc} member[x].
and so on. you can make these thin little functions that, as said above, effectively make it un-private by giving back full access. Or you can insert logic that does data validation or blocks the user from over-writing data after using a get or that prevents seeing info for other members (security, the user can see his own member record but not ALL member records kind of stuff), and so on.

I follow the 'getters and setters must do something' rule myself. That is, they need to validate or protect data or something, not just be a pass thru that makes it public (logically) and private (mechanically).

a quick example...
1
2
3
4
5
6
7
void Bank::pushback(Customer &c)
{
    if( validnamecheck(c.name) && validaddresscheck(c.address) && ..etc()) 
     customers.push_back(c);
    else
      complain_to_user("invalid customer data, customer not registered");
}

Last edited on
hello again!
Well, i did some research and I understood what you mean. What I was trying to achieve was to add some customers to a vector and the final scope of it is to write the customers entries in a data batase. I don't know what I was trying to do with the ostream when I had the push_back method. Actually i was trying to write the info in a file.
if I use a vector and add them with push_back and then connect it to a database?
is this a good idea or i am on the wrong way?
thx
it sounds fine to me.
thx :)
Topic archived. No new replies allowed.