Suppose we want to create a class for Graph. The class stores adjacency matrix representation of the graph. Therefore, our class structure would be something like below.
error: invalid use of non-static data member 'Graph::V'.
Even if we make V static, we get error “array bound is not an integer constant”
C++ doesn’t allow to create an stack allocated array in a class whose size is not constant. So we need to dynamically allocate memory. Below is a simple program to show how to dynamically allocate 2D array in a C++ class using a class for Graph with adjacency matrix representation.
0 1 1 0 0 0 1 0 1 0 0 1 0 0 0 1
A note on call of memset():
memset() is used separately for individual rows. We can’t replace these calls with one call because rows are allocated at different addresses and making a memset call like below would be disastrous.
// Wrong!! (Rows of matrix at different addresses) memset(adj, false, V*V*sizeof(bool));
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to create an unordered_map of user defined class in C++?
- How to create an unordered_set of user defined class or struct in C++?
- Program to create Custom Vector Class in C++
- How to create a custom String class in C++ with basic functionalities
- How to convert a class to another class type in C++?
- Difference between Base class and Derived class in C++
- Inline namespaces and usage of the "using" directive inside namespaces
- What happens when a virtual function is called inside a non-virtual function in C++
- Where is an object stored if it is created inside a block in C++?
- How to restrict dynamic allocation of objects in C++?
- new and delete operators in C++ for dynamic memory
- What is Dynamic Memory Allocation?
- Dynamic Constructor in C++ with Examples
- Difference between Static and Dynamic Memory Allocation in C
- Array of Strings in C++ (5 Different Ways to Create)
- What are the data types for which it is not possible to create an array?
- Array class in C++
- Does C++ compiler create default constructor when we write our own?
- When does compiler create default and copy constructors in C++?
- OpenCV C++ Program to create a single colored blank image