Declare And Initialize An Array Of Objects | C++ Tutorial

Тәжірибелік нұсқаулар және стиль

How to declare and initialize an array of objects in C++. Source code: github.com/por.... Check out www.portfolioc... to build a portfolio that will impress employers!

Пікірлер: 38

  • @rudy5360
    @rudy53602 жыл бұрын

    Thank you, exactly what I was trying to figure out! Now I know how to initialise an array of objects and call their constructor with parameters for each element!

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    You’re welcome Rudy, and that’s awesome I’m glad to hear it helped you out! :-)

  • @avinashthakur80
    @avinashthakur802 жыл бұрын

    To extend this, following are also possible, Square arr1[3] = { {1, "red"}, {2, "blue"}, {3, "green"} }; or, Square arr2[3] = { {1, "red"}, {}, // default initialized {3, "green"} }; or, Square arr3[3] = { {1, "red"}, // rest default initialized. };

  • @ylulnlulsYx1
    @ylulnlulsYx12 жыл бұрын

    If you can't change/want to change the constructor, just use malloc(): Square *squares = (Squares*)malloc(sizeof(Squares)*N) and iterate through with calling the constructor: for(int i = 0; i

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    Thank you for sharing this! :-)

  • @Time-py2sv
    @Time-py2sv Жыл бұрын

    I have learned more in this tutorial, than in two semesters of c++ programming. Thank you so much !

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    You're very welcome! :-) If you liked this video, these playlists may be of interest to you: C++ Tutorials: kzread.info/dash/bejne/o4uEzrSukrm3Y5s.html C++ Examples: kzread.info/dash/bejne/eJ9hm618crLZoJs.html

  • @HPcarnace

    @HPcarnace

    Жыл бұрын

    Maybe you don´t read BOOKS.

  • @bannfrancis9130

    @bannfrancis9130

    10 ай бұрын

    @@HPcarnaceyou don't have to read books, you have to practice! :D

  • @adamloepker8057
    @adamloepker8057 Жыл бұрын

    alright, the ability to call different constructors in a single array definition is pretty cool

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    I think so too Adam! :-)

  • @dwivedys
    @dwivedys2 ай бұрын

    Brilliant!!!! Learnt a hell of a lot here…

  • @OCEAN-fc9wl
    @OCEAN-fc9wl2 жыл бұрын

    We Appreciate your efforts! Keep making these videos

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    Thank you! :-) I have many, many, many more videos that I want to make on many different topics, I'm hoping to do this "forever". :-D

  • @OCEAN-fc9wl

    @OCEAN-fc9wl

    2 жыл бұрын

    @@PortfolioCourses Sounds wonderful!

  • @techademy9354
    @techademy93542 жыл бұрын

    Hey man, I just subscribed to your channel, I think this channel is underrated. You should have more subscribers given your amazing content👍🏼 Just want to ask, Im a CS student, and I dont recall being taught this on my programming courses. How is it usually used in real-life program (in workspace), because I assume you wouldn't call functions of an object manually one by one, so something like this would be used in a real-life work. Can you explain how objects are made in real programs?

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    Thank you for the kind words, I'm glad to hear you enjoy the channel! In C++ there's a lot of different ways to do things, in particular there's a lot of different ways to create objects. :-) So I wouldn't be surprised at all if your teachers didn't show you this technique in their classes. Objects are made in many different ways in real-programs, there isn't really a "real-world way". All the different approaches may be relevant in different scenarios. It's kind of a "best tool for the job" situation more than a "school vs real-world" situation. Many real-world applications use dynamically allocated objects using the keywords new and delete. Dynamically allocated data is common in many real-world applications. So that's something I'm planning on covering in a video in the near future that you may find interesting.

  • @techademy9354

    @techademy9354

    2 жыл бұрын

    @@PortfolioCourses Thanks for the insights, they are really helpful for me! School teaches basic stuffs, and they expect students would get it right away and be able to use it on huge projects. For example in dynamic memory allocation, we were only taught to dynamically allocate memory and just deallocate it (and basics of memory leaks etc). But in job situation, I dont think thats the case, we have to precisely know beforehand when and where we should allocate and deallocate memory dynamically. If we forgot to deallocate, there'll be memory leak for instance, and the scope of dynamic variables and pointers are confusing for beginners, especially when working in multiple classes.

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    @@techademy9354 I think that's why making larger portfolio projects is very important. When you make a larger application you're forced to deal with a lot of the issues that come up in "real-world" applications, and you learn more in the process. It may not be identical to the "real-world", but working on larger projects will help you learn things that you don't come across when making small solutions for class assignments or test questions for example.

  • @techademy9354

    @techademy9354

    2 жыл бұрын

    @@PortfolioCourses I really appreciate your time and insights! Thankyou so much man! I hope this channel can be a place for students and software engineers to find answers as well :) keep on doing this!

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    @@techademy9354 You're welcome... I won't stop doing this, and I also hope the channel becomes something very helpful for students. Any help spreading the word with classmates, on social media etc, is appreciated. :-D

  • @lucasgroves137
    @lucasgroves137 Жыл бұрын

    Hahaha (turns to wracking sobs)... I just dug through enough layers of lame, low-content CRAP made by inept wafflers in love with the sound of their own voices to match the kilometres of sediment on the ocean floor, before finally landing here. This array of objects with exactly this kind of attribute control is what I've just spent several hours mucking around trying to build. Thanks for laying it out clearly and succinctly, pitched exactly right for people who need to use it in real projects. ☑ Obviously I'm now subbed, especially since you didn't start the video with THAT ubiquitous, brainless liking and subbing prod, lmao. No wonder there are only 24 of us here; real content is far too dense and bland for the comfort levels of the typical lightweight consumer. 😂

  • @phoneixacademy4856
    @phoneixacademy4856 Жыл бұрын

    How to make constructor if the input to the object taken by for loop

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    You could collect the input with a function, and then call the constructor after that, for example. This is a design pattern called the factory pattern that might be a good idea to look at too: en.wikipedia.org/wiki/Factory_method_pattern. :-)

  • @framo_official
    @framo_official6 ай бұрын

    why is there an error at 4:20 and no error at 6:00`?

  • @HayzenAce

    @HayzenAce

    4 ай бұрын

    At 4:20, a Default Constructor i.e. a constructor with no arguments is not used. Since there already exists a two arguments Constructor. But at 6:00, a Default Constructor is explicitly provided with no arguments. Learn about Constructor Overloading for more clarification.

  • @guruprasaathpushparaj3307
    @guruprasaathpushparaj3307 Жыл бұрын

    Hi.. wonderful explanation. I have a doubt if we have a array of larger rows like square[100]. How can we declare user defined constructor for that?

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    I'm glad you enjoyed it Guru! :-) I'm not sure I 100% understand the question you're asking... if you want to declare and initialize an array of 100 squares, you could use the technique in this video the same way. If you wanted the array of 100 squares to be created "by something" and then "given" to your code, you might want to look at the factory pattern/method: en.wikipedia.org/wiki/Factory_method_pattern. The idea is to create a function that does the hard work of making "the thing" you want (i.e. an object, array, etc.).

  • @Dipits_Learning_Point
    @Dipits_Learning_Point Жыл бұрын

    how to take input from user in this case !

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    If we're using user input to initialize the array, then I would recommend to just declare the array above a loop, and then have a loop which is responsible for gathering the input from the user and creating each object and storing it in the array. :-)

  • @006daredevil
    @006daredevil Жыл бұрын

    why we can't declare an intialize an array inside a class in c++. Please explain I appreciate it.

  • @PortfolioCourses

    @PortfolioCourses

    Жыл бұрын

    It's ultimately "how the language was designed". It is possible to initialize an array as part of the constructor initialization list like this example: stackoverflow.com/a/10694754. :-)

  • @clistinisstanislawski5499
    @clistinisstanislawski54992 жыл бұрын

    Excellent video. Thank you. Here’s a question. Supposing that the array of objects had more space to store other objects. How would I push new objects into the array after the array was initialized?

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    When you initialize the array of objects, every element will contain an object. So in some sense their can't be "more space" because all of the elements are already set to an object, and there are no "blank elements" in the array. That said, perhaps you don't need some of the objects in the array, maybe you only need the first 4 objects in the array to start with and later on you will need additional objects. In this case, what you could do is an assignment to the element of the array where you would like to place the "new" object. Like in the below code. When you do an assignment like this with objects, it won't matter whether they are in the array or not, what will happen is a shallow copy: kzread.info/dash/bejne/hX6tlsF8mZuWftI.html. Essentially the member variables of one object get set to the values of the member variables of the other object. So in some sense we are not putting a "new" object into the array either, we are performing object assignment, which makes one object's member variables set to the same values as the other. #include using namespace std; class Test { public: int x; Test(int set_x) { x = set_x; } }; int main() { Test t1 = Test(1); Test t2 = Test(2); cout

  • @clistinisstanislawski5499

    @clistinisstanislawski5499

    2 жыл бұрын

    @@PortfolioCourses Thanks for answering my question. I haven't seen much about this matter on KZread tutorials. 🤝

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    @@clistinisstanislawski5499 No problem! :-)

  • @satyad5285
    @satyad52852 жыл бұрын

    WHEN WE USE CLASSES IN C++ IN SOLVING A PROBLEM AND HOW TO KNOW WHERE SHOULD WE HAVE TO USE IT . WHAT IS NEED OF OOPS IN C++ WHERE WE USE IT AND SHOULD WE HAVE TO USE OOPS CONCEPT IN EVERY PROGRAM WHAT DIFF OCCURS WHEN PROBLEM SOLVED IN C, AND C++? PLEASE REPLY😃😃😃😃

  • @PortfolioCourses

    @PortfolioCourses

    2 жыл бұрын

    This is a really, really good question. :-) A full answer is pretty long and complicated though, I think I will need to make a video on just this question. Basically, C++ includes object-oriented concepts like classes, inheritance and polymorphism that allow us to structure are programs and solve problems differently than in C. These concepts allow us to model problems in a different way that is often closer to the "real-world". So we can have a class for "company" and another class for "employee" and our company objects can then have an array of employee objects.... just like how a real company has some number of real employees. Often times structuring our programs in this way allows us to make them more reliable and less prone to errors and bugs. And when we use concepts like inheritance and polymorpishm, we can often re-use code we've previously written. So for example if we have full-time and part-time employees, we can create a general employee class, and then child classes for part-time and full-time employees that incorporate the differences for these types of employees while leveraging the similarities contained in the shared parent class. Virtually any program that we can write in C++, we can ultimately write in C too... if we're given enough time. :-) But the concepts in C++ allows us to write programs "better"in some instances. Anyways, this is a very large topic, I think I'll have to make a video on it later. :-)

Келесі