C++ :: How To Initialize Vector In A Class Object
Mar 6, 2013
I want to make a class, named generation, having a vector<chromosome> type data member.
chromosome is also class name.
chromosome has a 'route' as data member, which type is class TArrayI defined in ROOT package.
the size of route is to be fixed according to parameters of generation class object.
class chromosome{
public: chromosome(){;}
....
protected:
TArrayI route;
};
class generation{
public: generation(int PopSize=300, int numCity = 36){
.........
}
vector<chromosome> Population;
};
I want each element, chromosome of Population, to have a numCity size of route.
View 2 Replies
ADVERTISEMENT
Aug 12, 2013
I know what are pointer's and how to use them but there is one point i am not able to understand. Below is the example code
I understand everything in the below code except 1 thing why i am using pointer to base class object in vector int the main() Function?
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// base class
[Code] ...
Here is the lines of code i want to understand.
Code:
vector<Employee*> employees;
employees.push_back(&emp1);
employees.push_back(&mgr1);
I know if i will not use the pointer base class function "virtual double grossPay" will be called for both base class object and derived class object and when i will use pointer with reference to the object because base class function is virtual it will look for same function in derived class and if available it will execute it.
View 3 Replies
View Related
Oct 31, 2014
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
public Customer() {
Orders = new List<Order>();
}
}
This object is called as
var cust = new Customer
{
Id = 1, Name = "Khatana", [b]Orders.Add(new Order())[/b]
}
I want to ask, Orders.Add(new Order()) is a wrong way, but why..!!... as List<Order> already has been initialized in Customer constructor, then why it is again required to be initialized in object initialization.
Is this a correct way
List<Order> orders = new List<Order> {aaa.....bb....cc};
var cust = new Customer
{
id = 1, Name = "Khatana", Orders = new List<Order> { orders }
}
Why we need to initialize a list in an object initialization, where as the list has been already initialized in object constructor.
View 2 Replies
View Related
Oct 7, 2014
How to initialize a static member of a class with template, which type is related to a nested class?
This code works (without nested class):
#include<iostream>
using namespace std;
struct B{
B(){cout<<"here"<<endl;}
};
template<typename Z>
[Code] ,....
View 1 Replies
View Related
Feb 3, 2015
Getting back into programming after a few years off and a bit rusty.
My question is: Is this going to initialize the size of the vector array's position and color properly?
#include <GLFW/glfw3.h>
#include <vector>
class TerrainClass {
private:
struct VertexType {
std::vector<float> position[3];
[Code]...
View 6 Replies
View Related
Jan 21, 2013
The case is like
class B{
public:
somedata;
somefunction();
}
class A{
public:
data;
function();
}
in somefunction i want a pointer to current object of class A m new to c++
View 2 Replies
View Related
Feb 1, 2015
I am struggling to understand what the correct way to initialize instances of a class for object orient programming is.
If I am not mistaken, there are 2 methods to initialize an instance "instance_name" of CLASS1 by calling the constructor:
(1) CLASS1 instance_name(argument);
(2) CLASS1 instance_name=CLASS1(argument);
As it turns out, I cannot use method (1) when I try to initialize a private instance inside another class. But I can use it in the main() code. I hope the code below will explain what I mean. Why only method (2) will work inside another class? Or is there another fundamental mistake I am making?
(BTW: I used CodeBlocks 13.12 with GNU GCC compiler for this example)
#include <iostream>
using namespace std;
class CLASS1{
[Code].....
View 6 Replies
View Related
Jan 31, 2014
I have a class which I need to initialize some arrays upon its creation. At first, I tried doing it like I would in Java -
float xyzw[4] = {0, 0, 0, 0}
but that didn't work. Then I had someone suggest using initialization list. I have done so below-
#include <vector>
#include "Buffer.hpp"
class Vertex {
public:
Vertex() :
xyzw{ 0, 0, 0, 0 },
rgba{ 0, 0, 0, 0 },
[Code]....
However, the above code gives me the following error:
Error1error C2536: 'Vertex::Vertex::xyzw' : cannot specify explicit initializer for arrays
I am using Visual Studio 2013.
Also, is there any way to edit previous posts? I keep making mistakes with the code tags.
View 5 Replies
View Related
Jan 6, 2015
In my case, it involves making a wrapper class of sorts for the std::set. I'm wanting to go all-out on it and make some "fashionable" constructors for it, one of which being similar to C-style array initializations.
// C-array initialization.
int array[5] = { 1, 2, 3, 4, 5 };
// Some example usage of what I'm wanting.
Set<long> num_set = { 10, 20, 30, 40, 50 };
Set<std::string> str_set = { "Hello", "I", "am", "a", "set." };
I almost never overload operators when I work--if it can be done with a function, it's done with a function--but I realize that doesn't make the best user-experience when other people come across your code, so that's what I'm trying to improve.
It looks like I'm going to be needing to overload the = operator, no big deal. But the array segment is confusing, since {} is not an overloadable operator in C++.
View 2 Replies
View Related
Dec 13, 2012
#include "B.h"
class A {
public :
A()
{
s_b = new B();
b = new B();
[Code] ....
In my project i have seen static object as above . But not able to know what is the exact use of it and how they are different from general object .
View 2 Replies
View Related
Apr 17, 2013
"You cannot initialize the static data member in the class definition — that’s simply a blueprint for an object and initializing values for members are not allowed. You don’t want to initialize it in a constructor, because you want to increment it every time the constructor is called so the count of the number of objects created is accumulated."
Why don't you want to initialize it in a constructor?
Edit: Because every time it is called it will set it back to 0 or whatever the initializing value.
View 2 Replies
View Related
May 13, 2013
I need to create a class vector as a template and define operations on vectors.
And this is what I made.
#include<iostream>
using namespace std;
template<class T>
[Code].....
View 2 Replies
View Related
Apr 26, 2014
I have my main.cpp like this:
#include <iostream>
#include "curve1.h"
#include "curve2.h"
using namespace std;
int main() {
Curve1 curve1Obj;
Curve2 curve2Obj;
[Code]...
Base class Score has two derived classes Curve1 and Curve2. There are two curve() functions, one is in Curve1 and other in Curve2 classes. getSize() returns the value of iSize.
My base class header score.h looks like this:
#ifndef SCORE_H
#define SCORE_H
class Score {
private:
int *ipScore;
float fAverage;
int iSize;
[Code]...
You can see that I have used curve1Obj to enter scores, calculate average and output. So if I call getSize() function with cuve1Obj, it gives the right size that I took from user in enterScores() function. Also the result is same if I call getSize() in score.cpp definition file in any of the functions (obviously).
.....
The problem is when I call curve() function of Curve2 class in main (line 23) with the object curve2Obj, it creates a new set of ipScore, fAverage and iSize (i think?) with garbage values. So when I call getSize() in curve() definition in curve2.cpp, it outputs the garbage. .....
How can I cause it to return the old values that are set in curve1.cpp?
Here is my curve2.cpp
#include <iostream>
#include "curve2.h"
using namespace std;
void Curve2::curve() {
cout << "getSize() returns: " << getSize() << endl; // out comes the garbage
}
Can I use a function to simply put values from old to new variables? If yes then how?
View 3 Replies
View Related
Aug 21, 2013
I am writing a program which is using SDL library. I have two different classes which one of them is Timer Class and the other is EventHandling Class.
I need to use some member functions and variables of Timer in some Eventhandling Class member functions, Although I want to define an object of Timer in int main {} and relate it to its member function that has been used in Eventhandling member function in order that it becomes easier to handle it, I mean that I want to have for example two objects of timer and two objects of Eventhandling class for two different users.
I do not know how to relate an object of a class from int main{} to its member function which is being used in another class member function.
Lets have it as a sample code:
class Timer {
private:
int x;
public:
Timer();
get_X();
start_X();
[Code] ....
View 4 Replies
View Related
Oct 24, 2013
I'm new to C++ especially vectors.. I've a question regarding sorting of object in a vector.. My object consists of x,y and civ. so I would like to know how do I sort the value of the civ in an descending order but at the same time retaining the value of x and y attached to it..
original
X: 4 Y: 5 CIV: 10
X: 3 Y: 2 CIV: 30
X: 3 Y: 3 CIV: 05
sorted
X: 3 Y: 2 CIV: 30
X: 4 Y: 5 CIV: 10
X: 3 Y: 3 CIV: 05
missionplan.cpp
void MissionPlan::topfives() {
stable_sort (topfive.begin(), topfive.end());
pointtwoD = topfive.at(i);
pointtwoD.displayPointdata();
}
View 2 Replies
View Related
Apr 4, 2012
I am erasing a object from the vector. I want to know that do i need to delete the object before I call the erase method or calling the vector erase method is suffice. See the following example.
Class A {
int val;
};
Class B {
vector<A *> vectorA;
void AddA(int val) {
A *a = new A;
a->val = val;
vectorA.push_back(a);
[Code] ....
I don't know which DeleteVectorEntry to use which makes sure that there is no memory leak in my program.
View 8 Replies
View Related
Jan 28, 2015
I'm working on collision detection for a game in SFML. I successfully designed a Spatial Partition grid to speed up the collision test, in the following of this tutorial: [URL] ....
But now I have an issue with one aspect of it: Going through a vector of objects and testing all the OTHER objects in the vector against said object. The author puts it into psueudocode here:
For each tick of the clock
For every object in the game
Get all the other objects in the same grid square
For each other object in the same grid square
I have trouble with the last line, because in iterating through a vector I am not sure how to skip over the current object. Here is my own code (a couple of sysntax errors but this is a c++ question not an SFML question):
//for every moveable object
for(int i = 0; i < rects_.size(); i++){
std::vector<sf::RectangleShape> posibleObjects_; //this will be a vector of WorldObjects in a real game
//for every object in that object's gridsquare
for(int j = 0; j < rects_.size(); j++){
if(rects_[i].intersects(rects_[j])){
//collision
} } }
The problem is, a collision will always be reported because somewhere in the vector the object will eventually check against itself which is always a true collision. What is the correct way to do this?
View 11 Replies
View Related
Sep 21, 2013
Here's my code so far:
case DELETE_TITLE:
std::cout << "Game to remove from list: ";
std::cin.ignore();
getline(std::cin, gameTitle);
for (iter = gameList.begin(); iter != gameList.end(); ++iter) {
[code]....
It deletes the text from the string but not the index it self.
It deletes the text but when I print the list of game titles it has it there blank. I want it to completely remove the object from the vector from where it was deleted
View 1 Replies
View Related
Sep 4, 2014
Lets say for example I have the following vector:
vector<Component*> mComponents;
and a function print() inside of class Component that prints the objects name.
How do I loop/iterate through the vector to access the print function in each object.
View 1 Replies
View Related
Dec 14, 2014
I have this class I have been working with,
Code:
// objects to hold results, row id, and name
class result_holder {
public:
// initialize class members
result_holder() : row_id(0), row_value(0.0), row_name("") { }
[Code] ....
There are cases where I need to find an object based on the value of row_id and delete the object from the vector row_results. I could find the proper object by looping through the vector and testing against each member.
Code:
// id I am looking for
unsigned int id_to_delete = 12;
for(i=0; i<row_results.size(); i++) {
if(id_to_delete == row_results[i].row_id) {
delete row_results[i];
}
}
I have used find before to find the position in a vector with a specific value, but I don't know how to use find to locate a specific value for an object member.
Also, is delete what I need to get rid of the object or should I be using erase as in,
Code:
// id I am looking for
unsigned int id_to_delete = 12;
for(i=0; i<row_results.size(); i++) {
if(id_to_delete == row_results[i].row_id) {
row_results.erase(row_results.begin()+i);
}
}
View 4 Replies
View Related
Sep 20, 2013
Suppose I have two classes A and B so how to access object of class A in constructor of B's class as a parameter.
View 6 Replies
View Related
Feb 20, 2015
My thought is that I would need to establish a variable for the class in the header and call the class within the .cpp file
//class A.h
B b;
Then in class A, to create the object and use a method from the object I would -
//class A.cpp
A::A(){
b();
}
int someAmethod(){
b.bmethod();
}
View 6 Replies
View Related
Mar 7, 2014
I have a class MySeqBuildBlockModule that I am inheriting from: public SeqBuildBlock. Other than constructor and destructor, this class MySeqBuildBlockModule has a method: prep.
class MySeqBuildBlockModule: public SeqBuildBlock {
friend class SeqBuildBlockIRns;
public:
MySeqBuildBlockModule (SBBList* pSBBList0, long TI1_In, long TI2_In)// more arguements in this constructor of derived class
: SeqBuildBlock (pSBBList0)
[code]....
I would have like to intiantiate an object "myIRns_3" of a class defined in third party library
SeqBuildBlockIRns myIRns_3(pSBBList2);
and would like to access it from the prep function as:
double dEnergyAllSBBs_DK = myIRns_3.getEnergyPerRequest();
I tried to instantiate following in either private section or in constructor; but w/o any success:
SeqBuildBlockIRns myIRns_3(pSBBList2);
ERRORS encountered:
When I tried to do it inside the constructor, I get the following errors:
MySBBModule.h(113) : error C2065: 'myIRns_3' : undeclared identifier
MySBBModule.h(113) : error C2228: left of '.getEnergyPerRequest' must have class/struct/union type
MySBBModule.h(116) : error C2065: 'pSBBList' : undeclared identifier
MySBBModule.h(116) : error C2227: left of '->prepSBBAll' must point to class/struct/union
When I tried to do it in private section, I get the following errors:
MySBBModule.h(106) : error C2061: syntax error : identifier 'pSBBList2'
MySBBModule.h(113) : error C2228: left of '.getEnergyPerRequest' must have class/struct/union type
MySBBModule.h(116) : error C2065: 'pSBBList' : undeclared identifier
MySBBModule.h(116) : error C2227: left of '->prepSBBAll' must point to class/struct/union
View 5 Replies
View Related
Apr 25, 2015
I'm working on a grocery store inventory project. One part is to have a shopping cart, where customers can put in up to 20 items. Because there can be up to 20 shopping carts at one time, I want to use a vector inside the cart object to represent all the individual food items.
Here's my code,
Header:
#ifndef CART_H
#define CART_H
#include <vector>
class Cart {
public:
Cart();
Cart(std::vector< int >, std::vector< int >)
[Code] ....
View 9 Replies
View Related
Jul 14, 2014
Information:
I'm using Code::Blocks v12.11.
(I'm using C++/SDL2, but I think that's of no relevance)
Problem:
I create a class named "CSprite" in a "Sprite.hpp"-file. I create a "Sprite.cpp"-file, which includes the "Sprite.hpp"-file. I define the methods of the class "CSprite" in the "Sprite.cpp"-file.
When I try to create an object of "CSprite" in the class named "CPlayer" in the file "Player.hpp" I get an error message. (<-- Looks complicated I know, the code example will be more usefull than this)
Error in the build messages:
C:UsersLinoDocuments1 Data LinoFreizeit1 ProgrammierenC++ & SDL2The Running ManCPlayer.h|30|error: 'CSprite' does not name a type|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 1 seconds) ===|
Code Example:
Sprite.hpp
#ifndef _SPRITE_HPP_
#define _SPRITE_HPP_
class CSprite {
[Code] .....
What did I miss? Did I include the wrong file? Or did I Forget to include the file? Why do I get the error message?
I also tried it with a pointer declaration and the "->" Operator but I got the same error message. I know I could just write a new function to load the texture in my "CPlayer"-class but this would not really answer my question.
View 15 Replies
View Related
Nov 9, 2013
I fully understand that a variable of one simple data type cannot be assigned to another of a different data type in an assignment statement, except when type-conversion(i.e. casting) is employed. For structured data types (like classes), I know that the assignment operator can be overloaded; but this only addresses objects of the same type.
My problem is that I have read data from an input file into an object of one class, but I want to transfer the contents into an object of a different class in an assignment statement. Can this be realized given that the two operands of the assignment operator (=), in this case, would be of two different types?
View 5 Replies
View Related