Search Results

Search found 9215 results on 369 pages for 'double pointers'.

Page 1/369 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Pointers in C vs No pointers in PHP

    - by AnnaBanana
    Both languages have the same syntax. Why does C have the weird * character that denotes pointers (which is some kind of memory address of the variable contents?), when PHP doesn't have it and you can do pretty much the same things in PHP that you can do in C, without pointers? I guess the PHP compiler handles this internally, why doesn't C do the same? Doesn't this add unneeded complexity in C? For example I don't understand them :)

    Read the article

  • C++ Pointers: Number of levels of Indirection

    - by A B
    In a C++ program that doesn't contain legacy C code, is there a guideline regarding the maximum number of levels of indirection that should be used in the source code? I know that in C (as opposed to C++), some programmers have used pointers to pointers for a multiple dimension array, but for the case of arrays, there are data structures in C++ that can be used to avoid the pointers to pointers. Are users who still create pointers to pointers (or more than this) trying to use pointers to pointers only for performance ETC. reasons? I have tried NOT to use any more than a pointer to a pointer, only in the case that a pointer needed modification; does anyone have any other official or unofficial guidelines or rules regarding the number of levels of indirection?

    Read the article

  • C++ smart pointers: sharing pointers vs. sharing data

    - by Eli Bendersky
    In this insightful article, one of the Qt programmers tries to explain the different kinds of smart pointers Qt implements. In the beginning, he makes a distinction between sharing data and sharing the pointers themselves: First, let’s get one thing straight: there’s a difference between sharing pointers and sharing data. When you share pointers, the value of the pointer and its lifetime is protected by the smart pointer class. In other words, the pointer is the invariant. However, the object that the pointer is pointing to is completely outside its control. We don’t know if the object is copiable or not, if it’s assignable or not. Now, sharing of data involves the smart pointer class knowing something about the data being shared. In fact, the whole point is that the data is being shared and we don’t care how. The fact that pointers are being used to share the data is irrelevant at this point. For example, you don’t really care how Qt tool classes are implicitly shared, do you? What matters to you is that they are shared (thus reducing memory consumption) and that they work as if they weren’t. Frankly, I just don't undersand this explanation. There was a clarification plea in the article comments, but I didn't find the author's explanation sufficient. If you do understand this, please explain. What is this distinction, and how are other shared pointer classes (i.e. from boost or the new C++ standards) fit into this taxonomy? Thanks in advance

    Read the article

  • What's a nice explanation for pointers?

    - by Macneil
    In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective? For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)? In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized. Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you. For example: I only somewhat understood pointers syntactically in C. I heard two of my friends explaining pointers to another friend, who asked why a struct was passed with a pointer. The first friend talked about how it needed to be referenced and modified, but it was just a short comment from the other friend where it hit me: "It's also more efficient." Passing 4 bytes instead of 16 bytes was the final conceptual shift I needed.

    Read the article

  • How is precedence determined in C pointers?

    - by ankur.trapasiya
    I've come across two pointer declarations that I'm having trouble understanding. My understanding of precedence rules goes something like this: Operator Precedence Associativity (), [ ] 1 Left to Right *, identifier 2 Right to Left Data type 3 But even given this, I can't seem to figure out how to evaluate the following examples correctly: First example float * (* (*ptr)(int))(double **,char c) My evaluation: *(ptr) (int) *(*ptr)(int) *(*(*ptr)(int)) Then, double ** char c Second example unsigned **( * (*ptr) [5] ) (char const *,int *) *(ptr) [5] *(*ptr)[5] *(*(*ptr)[5]) **(*(*ptr)[5]) How should I read them?

    Read the article

  • C# (4): double minus double giving precision problems

    - by thermal7
    I have come across a precision issue with double in .NET I thought this only applied to floats but now I see that double is a float. double test = 278.97 - 90.46; Debug.WriteLine(test) //188.51000000000005 //correct answer is 188.51 What is the correct way to handle this? Round? Lop off the unneeded decimal places?

    Read the article

  • pointers to functions

    - by DevAno1
    I have two basic Cpp tasks, but still I have problems with them. First is to write functions mul1,div1,sub1,sum1, taking ints as arguments and returning ints. Then I need to create pointers ptrFun1 and ptrFun2 to functions mul1 and sum1, and print results of using them. Problem starts with defining those pointers. I thought I was doing it right, but devcpp gives me errors in compilation. #include <iostream> using namespace std; int mul1(int a,int b) { return a * b; } int div1(int a,int b) { return a / b; } int sum1(int a,int b) { return a + b; } int sub1(int a,int b) { return a - b; } int main() { int a=1; int b=5; cout << mul1(a,b) << endl; cout << div1(a,b) << endl; cout << sum1(a,b) << endl; cout << sub1(a,b) << endl; int *funPtr1(int, int); int *funPtr2(int, int); funPtr1 = sum1; funPtr2 = mul1; cout << funPtr1(a,b) << endl; cout << funPtr2(a,b) << endl; system("PAUSE"); return 0; } 38 assignment of function int* funPtr1(int, int)' 38 cannot convertint ()(int, int)' to `int*()(int, int)' in assignment Task 2 is to create array of pointers to those functions named tabFunPtr. How to do that ?

    Read the article

  • Using pointers in PHP.

    - by Babiker
    I ask this question because i learned that in programming and designing, you must have a good reason for decisions. I am php learner and i am at a crossroad here, i am using simple incrementation to try to get what im askin across. I am certainly not here to start a debate about the pros/cons of pointers but when it comes to php, which is the better programming practice: function increment(&$param) { $param++; } Or function increment($param){ return $param++; } $param = increment($param);

    Read the article

  • handling refrence to pointers/double pointers using SWIG [C++ to Java]

    - by Siddu
    My code has an interface like class IExample { ~IExample(); //pure virtual methods ...}; a class inheriting the interface like class CExample : public IExample { protected: CExample(); //implementation of pure virtual methods ... }; and a global function to create object of this class - createExample( IExample *& obj ) { obj = new CExample(); } ; Now, I am trying to get Java API wrapper using SWIG, the SWIG generated interface has a construcotr like - IExample(long cPtr, boolean cMemoryOwn) and global function becomes createExample(IExample obj ) The problem is when i do, IExample exObject = new IExample(LogFileLibraryJNI.new_plong(), true /*or false*/ ); createExample( exObject ); The createExample(...) API at C++ layer succesfully gets called, however, when call returns to Java layer, the cPtr (long) variable does not get updated. Ideally, this variable should contain address of CExample object. I read in documentation that typemaps can be used to handle output parameters and pointer references as well; however, I am not able to figure out the suitable way to use typemaps to resolve this problem, or any other workaround. Please suggest if i am doing something wrong, or how to use typemap in such situation?

    Read the article

  • Using delegates in C# (Part 2)

    - by rajbk
    Part 1 of this post can be read here. We are now about to see the different syntaxes for invoking a delegate and some c# syntactic sugar which allows you to code faster. We have the following console application. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: Operation op1 = new Operation(Division); 9: double result = op1.Invoke(10, 5); 10: 11: Console.WriteLine(result); 12: Console.ReadLine(); 13: } 14: 15: static double Division(double x, double y) { 16: return x / y; 17: } 18: } Line 1 defines a delegate type called Operation with input parameters (double x, double y) and a return type of double. On Line 8, we create an instance of this delegate and set the target to be a static method called Division (Line 15) On Line 9, we invoke the delegate (one entry in the invocation list). The program outputs 5 when run. The language provides shortcuts for creating a delegate and invoking it (see line 9 and 11). Line 9 is a syntactical shortcut for creating an instance of the Delegate. The C# compiler will infer on its own what the delegate type is and produces intermediate language that creates a new instance of that delegate. Line 11 uses a a syntactical shortcut for invoking the delegate by removing the Invoke method. The compiler sees the line and generates intermediate language which invokes the delegate. When this code is compiled, the generated IL will look exactly like the IL of the compiled code above. 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //shortcut constructor syntax 9: Operation op1 = Division; 10: //shortcut invoke syntax 11: double result = op1(10, 2); 12: 13: Console.WriteLine(result); 14: Console.ReadLine(); 15: } 16: 17: static double Division(double x, double y) { 18: return x / y; 19: } 20: } C# 2.0 introduced Anonymous Methods. Anonymous methods avoid the need to create a separate method that contains the same signature as the delegate type. Instead you write the method body in-line. There is an interesting fact about Anonymous methods and closures which won’t be covered here. Use your favorite search engine ;-)We rewrite our code to use anonymous methods (see line 9): 1: public delegate double Operation(double x, double y); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: //Anonymous method 9: Operation op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } We could rewrite our delegate to be of a generic type like so (see line 2 and line 9). You will see why soon. 1: //Generic delegate 2: public delegate T Operation<T>(T x, T y); 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: Operation<double> op1 = delegate(double x, double y) { 10: return x / y; 11: }; 12: double result = op1(10, 2); 13: 14: Console.WriteLine(result); 15: Console.ReadLine(); 16: } 17: 18: static double Division(double x, double y) { 19: return x / y; 20: } 21: } The .NET 3.5 framework introduced a whole set of predefined delegates for us including public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); Our code can be modified to use this delegate instead of the one we declared. Our delegate declaration has been removed and line 7 has been changed to use the Func delegate type. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //Func is a delegate defined in the .NET 3.5 framework 7: Func<double, double, double> op1 = delegate (double x, double y) { 8: return x / y; 9: }; 10: double result = op1(10, 2); 11: 12: Console.WriteLine(result); 13: Console.ReadLine(); 14: } 15: 16: static double Division(double x, double y) { 17: return x / y; 18: } 19: } .NET 3.5 also introduced lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. We change our code to use lambda expressions. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //lambda expression 7: Func<double, double, double> op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } C# 3.0 introduced the keyword var (implicitly typed local variable) where the type of the variable is inferred based on the type of the associated initializer expression. We can rewrite our code to use var as shown below (line 7).  The implicitly typed local variable op1 is inferred to be a delegate of type Func<double, double, double> at compile time. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: //implicitly typed local variable 7: var op1 = (x, y) => x / y; 8: double result = op1(10, 2); 9: 10: Console.WriteLine(result); 11: Console.ReadLine(); 12: } 13: 14: static double Division(double x, double y) { 15: return x / y; 16: } 17: } You have seen how we can write code in fewer lines by using a combination of the Func delegate type, implicitly typed local variables and lambda expressions.

    Read the article

  • C++ simple arrays and pointers question

    - by nashmaniac
    So here's the confusion, let's say I declare an array of characters char name[3] = "Sam"; and then I declare another array but this time using pointers char * name = "Sam"; What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters? Also how is it different from char * name = new char[3]; If those three are different where should they be used I mean in what circumstances?

    Read the article

  • What's so bad about pointers in C++?

    - by Martin Beckett
    To continue the discussion in Why are pointers not recommended when coding with C++ Suppose you have a class that encapsulates objects which need some initialisation to be valid - like a network socket. // Blah manages some data and transmits it over a socket class socket; // forward declaration, so nice weak linkage. class blah { ... stuff TcpSocket *socket; } ~blah { // TcpSocket dtor handles disconnect delete socket; // or better, wrap it in a smart pointer } The ctor ensures that socket is marked NULL, then later in the code when I have the information to initialise the object. // initialising blah if ( !socket ) { // I know socket hasn't been created/connected // create it in a known initialised state and handle any errors // RAII is a good thing ! socket = new TcpSocket(ip,port); } // and when i actually need to use it if (socket) { // if socket exists then it must be connected and valid } This seems better than having the socket on the stack, having it created in some 'pending' state at program start and then having to continually check some isOK() or isConnected() function before every use. Additionally if TcpSocket ctor throws an exception it's a lot easier to handle at the point a Tcp connection is made rather than at program start. Obviously the socket is just an example, but I'm having a hard time thinking of when an encapsulated object with any sort of internal state shouldn't be created and initialised with new.

    Read the article

  • Dangling pointers and double free

    - by user151410
    After some painful experiences, I understand the problem of dangling pointers and double free. I am seeking proper solutions. aStruct has a number of fields including other arrays. aStruct *A=NULL, *B = NULL; A = (aStruct*) calloc(1, sizeof(sStruct)); B = A; free_aStruct(A); ... //bunch of other code in various places. ... free_aStruct(B); Is there any way to write free_aStruct(X) so that free_aStruct(B) exists gracefully?? void free_aStruct(aStruct *X){ if (X ! = NULL){ if (X->a != NULL){free(X->a); x->a = NULL;} free(X); X = NULL; } } Doing above only sets A = NULL when free_aStruct(A); is called. B is now dangling. How can this situation be avoided / remedied? Is reference counting the only viable solution? or, are there other "defensive" free approaches, to prevent free_aStruct(B); from exploding? Thanks, Russ

    Read the article

  • introducing pointers to a large software project

    - by stefan
    I have a fairly large software project written in c++. In there, there is a class foo which represents a structure (by which i don't mean the programmers struct) in which foo-objects can be part of a foo-object. Here's class foo in simplest form: class Foo { private: std::vector<unsigned int> indices; public: void addFooIndex(unsigned int); unsigned int getFooIndex(unsigned int); }; Every foo-object is currently stored in an object of class bar. class Bar { private: std::vector<Foo> foos; public: void addFoo(Foo); std::vector<Foo> getFoos(); } So if a foo-object should represent a structure with a "inner" foo-object, I currently do Foo foo; Foo innerFoo; foo.addFooIndex(bar.getFoos().size() - 1); bar.addFoo(innerFoo); And to get it, I obviously use: Foo foo; for ( unsigned int i = 0; i < foo.getFooIndices().size(); ++i ) { Foo inner_foo; assert( foo.getFooIndices().at(i) < bar.getFoos().size() ); inner_foo = bar.getFoos().at(foo.getFooIndices().at(i)); } So this is not a problem. It just works. But it's not the most elegant solution. I now want to make the inner foos to be "more connected" with the foo-object. It would be obviously to change class foo to: class Foo { private: std::vector<Foo*> foo_pointers; public: void addFooPointer(Foo*); std::vector<Foo*> getFooPointers(); }; So now, for my question: How to gently change this basic class without messing up the whole code? Is there a "clean way"?

    Read the article

  • Functions returning pointers

    - by fg nu
    C++ noob here. I have a very basic question about a construct I found in the C++ book I am reading. // class declaration class CStr { char sData[256]; public: char* get(void); }; // implementation of the function char* CStr::get(void) { return sData; } So the Cstr::get function is obviously meant to return a character pointer, but the function is passing what looks like the value (return sData). Does C++ know to return the address of the returned object? My guess would have been that the function definition would be return &sData.

    Read the article

  • Weird behavior when using pointers [migrated]

    - by Kinan Al Sarmini
    When I run this code on MS VS C++ 2010: #include <iostream> int main() { const int a = 10; const int *b = &a; int *c = (int *)b; *c = 10000; std::cout << c << " " << &a << std::endl; std::cout << *c << " " << a << " " << *(&a) << std::endl; return 0; } The output is: 0037F784 0037F784 10000 10 10 The motivation for writing that code was this sentence from "The C++ Programming Language" by Stroustrup: "It is possible to explicitly remove the restrictions on a pointer to const by explicit type conversion". I know that trying to modify a constant is conceptually wrong, but I find this result quite weird. Can anyone explain the reason behind it?

    Read the article

  • How to rotate a set of points on z = 0 plane in 3-D, preserving pairwise distances?

    - by cagirici
    I have a set of points double n[] on the plane z = 0. And I have another set of points double[] m on the plane ax + by + cz + d = 0. Length of n is equal to length of m. Also, euclidean distance between n[i] and n[j] is equal to euclidean distance between m[i] and m[j]. I want to rotate n[] in 3-D, such that for all i, n[i] = m[i] would be true. In other words, I want to turn a plane into another plane, preserving the pairwise distances. Here's my code in java. But it does not help so much: double[] rotate(double[] point, double[] currentEquation, double[] targetEquation) { double[] currentNormal = new double[]{currentEquation[0], currentEquation[1], currentEquation[2]}; double[] targetNormal = new double[]{targetEquation[0], targetEquation[1], targetEquation[2]}; targetNormal = normalize(targetNormal); double angle = angleBetween(currentNormal, targetNormal); double[] axis = cross(targetNormal, currentNormal); double[][] R = getRotationMatrix(axis, angle); return rotated; } double[][] getRotationMatrix(double[] axis, double angle) { axis = normalize(axis); double cA = (float)Math.cos(angle); double sA = (float)Math.sin(angle); Matrix I = Matrix.identity(3, 3); Matrix a = new Matrix(axis, 3); Matrix aT = a.transpose(); Matrix a2 = a.times(aT); double[][] B = { {0, axis[2], -1*axis[1]}, {-1*axis[2], 0, axis[0]}, {axis[1], -1*axis[0], 0} }; Matrix A = new Matrix(B); Matrix R = I.minus(a2); R = R.times(cA); R = R.plus(a2); R = R.plus(A.times(sA)); return R.getArray(); } This is what I get. The point set on the right side is actually part of a point set on the left side. But they are on another plane. Here's a 2-D representation of what I try to do: There are two lines. The line on the bottom is the line I have. The line on the top is the target line. The distances are preserved (a, b and c). Edit: I have tried both methods written in answers. They both fail (I guess). Method of Martijn Courteaux public static double[][] getRotationMatrix(double[] v0, double[] v1, double[] v2, double[] u0, double[] u1, double[] u2) { RealMatrix M1 = new Array2DRowRealMatrix(new double[][]{ {1,0,0,-1*v0[0]}, {0,1,0,-1*v0[1]}, {0,0,1,0}, {0,0,0,1} }); RealMatrix M2 = new Array2DRowRealMatrix(new double[][]{ {1,0,0,-1*u0[0]}, {0,1,0,-1*u0[1]}, {0,0,1,-1*u0[2]}, {0,0,0,1} }); Vector3D imX = new Vector3D((v0[1] - v1[1])*(u2[0] - u0[0]) - (v0[1] - v2[1])*(u1[0] - u0[0]), (v0[1] - v1[1])*(u2[1] - u0[1]) - (v0[1] - v2[1])*(u1[1] - u0[1]), (v0[1] - v1[1])*(u2[2] - u0[2]) - (v0[1] - v2[1])*(u1[2] - u0[2]) ).scalarMultiply(1/((v0[0]*v1[1])-(v0[0]*v2[1])-(v1[0]*v0[1])+(v1[0]*v2[1])+(v2[0]*v0[1])-(v2[0]*v1[1]))); Vector3D imZ = new Vector3D(findEquation(u0, u1, u2)); Vector3D imY = Vector3D.crossProduct(imZ, imX); double[] imXn = imX.normalize().toArray(); double[] imYn = imY.normalize().toArray(); double[] imZn = imZ.normalize().toArray(); RealMatrix M = new Array2DRowRealMatrix(new double[][]{ {imXn[0], imXn[1], imXn[2], 0}, {imYn[0], imYn[1], imYn[2], 0}, {imZn[0], imZn[1], imZn[2], 0}, {0, 0, 0, 1} }); RealMatrix rotationMatrix = MatrixUtils.inverse(M2).multiply(M).multiply(M1); return rotationMatrix.getData(); } Method of Sam Hocevar static double[][] makeMatrix(double[] p1, double[] p2, double[] p3) { double[] v1 = normalize(difference(p2,p1)); double[] v2 = normalize(cross(difference(p3,p1), difference(p2,p1))); double[] v3 = cross(v1, v2); double[][] M = { { v1[0], v2[0], v3[0], p1[0] }, { v1[1], v2[1], v3[1], p1[1] }, { v1[2], v2[2], v3[2], p1[2] }, { 0.0, 0.0, 0.0, 1.0 } }; return M; } static double[][] createTransform(double[] A, double[] B, double[] C, double[] P, double[] Q, double[] R) { RealMatrix c = new Array2DRowRealMatrix(makeMatrix(A,B,C)); RealMatrix t = new Array2DRowRealMatrix(makeMatrix(P,Q,R)); return MatrixUtils.inverse(c).multiply(t).getData(); } The blue points are the calculated points. The black lines indicate the offset from the real position.

    Read the article

  • Invalid conversion from int to int** C++

    - by user69514
    Not sure why I'm getting this error. I have the following: int* arr = new int[25]; int* foo(){ int* i; cout << "Enter an integer:"; cin >> *i; return i; } void test(int** myInt){ *myInt = foo(); } This call here is where I get the error: test(arr[0]); //here i get invalid conversion from int to int**

    Read the article

  • dividing double by double gives weird results - Java

    - by Aly
    Hi, I am trying to do the following 33.33333333333333/100.0 to get 0.333333333333333 however when I run System.out.println(33.33333333333333/100.0); I get 0.33333333333333326 as the output, similarly when I run System.out.println(33.33333333333333/1000.0); I get 0.033333333333333326 as the output. Does anyone know why, and how I can get the correct value (without loss of decimal places). Thanks

    Read the article

  • invasive vs non-invasive ref-counted pointers in C++

    - by anon
    For the past few years, I've generally accepted that if I am going to use ref-counted smart pointers invasive smart pointers is the way to go -- However, I'm starting to like non-invasive smart pointers due to the following: I only use smart pointers (so no Foo* lying around, only Ptr) I'm starting to build custom allocators for each class. (So Foo would overload operator new). Now, if Foo has a list of all Ptr (as it easily can with non-invasive smart pointers). Then, I can avoid memory fragmentation issues since class Foo move the objects around (and just update the corresponding Ptr). The only reason why this Foo moving objects around in non-invasive smart pointers being easier than invasive smart pointers is: In non-invasive smart pointers, there is only one pointer that points to each Foo. In invasive smart pointers, I have no idea how many objects point to each Foo. Now, the only cost of non-invasive smart pointers ... is the double indirection. [Perhaps this screws up the caches]. Does anyone have a good study of expensive this extra layer of indirection is?

    Read the article

  • Why do you need float/double?

    - by acidzombie24
    I was watching http://www.joelonsoftware.com/items/2011/06/27.html and laughed at Jon Skeet joke about 0.3 not being 0.3. I personally never had problems with floats/decimals/doubles but then I remember I learned 6502 very early and never needed floats in most of my programs. The only time I used it was for graphics and math where inaccurate numbers were ok and the output was for the screen and not to be stored (in a db, file) or dependent on. My question is, where are places were you typically use floats/decimals/double? So I know to watch out for these gotchas. With money I use longs and store values by the cent, for speed of an object in a game I add ints and divide (or bitshift) the value to know if I need to move a pixel or not. (I made object move in the 6502 days, we had no divide nor floats but had shifts). So I was mostly curious.

    Read the article

  • Vector of Object Pointers, general help and confusion

    - by Staypuft
    Have a homework assignment in which I'm supposed to create a vector of pointers to objects Later on down the load, I'll be using inheritance/polymorphism to extend the class to include fees for two-day delivery, next day air, etc. However, that is not my concern right now. The final goal of the current program is to just print out every object's content in the vector (name & address) and find it's shipping cost (weight*cost). My Trouble is not with the logic, I'm just confused on few points related to objects/pointers/vectors in general. But first my code. I basically cut out everything that does not mater right now, int main, will have user input, but right now I hard-coded two examples. #include <iostream> #include <string> #include <vector> using namespace std; class Package { public: Package(); //default constructor Package(string d_name, string d_add, string d_zip, string d_city, string d_state, double c, double w); double calculateCost(double, double); void Print(); ~Package(); private: string dest_name; string dest_address; string dest_zip; string dest_city; string dest_state; double weight; double cost; }; Package::Package() { cout<<"Constucting Package Object with default values: "<<endl; string dest_name=""; string dest_address=""; string dest_zip=""; string dest_city=""; string dest_state=""; double weight=0; double cost=0; } Package::Package(string d_name, string d_add, string d_zip, string d_city, string d_state, string r_name, string r_add, string r_zip, string r_city, string r_state, double w, double c){ cout<<"Constucting Package Object with user defined values: "<<endl; string dest_name=d_name; string dest_address=d_add; string dest_zip=d_zip; string dest_city=d_city; string dest_state=d_state; double weight=w; double cost=c; } Package::~Package() { cout<<"Deconstructing Package Object!"<<endl; delete Package; } double Package::calculateCost(double x, double y){ return x+y; } int main(){ double cost=0; vector<Package*> shipment; cout<<"Enter Shipping Cost: "<<endl; cin>>cost; shipment.push_back(new Package("tom r","123 thunder road", "90210", "Red Bank", "NJ", cost, 10.5)); shipment.push_back(new Package ("Harry Potter","10 Madison Avenue", "55555", "New York", "NY", cost, 32.3)); return 0; } So my questions are: I'm told I have to use a vector of Object Pointers, not Objects. Why? My assignment calls for it specifically, but I'm also told it won't work otherwise. Where should I be creating this vector? Should it be part of my Package Class? How do I go about adding objects into it then? Do I need a copy constructor? Why? What's the proper way to deconstruct my vector of object pointers? Any help would be appreciated. I've searched for a lot of related articles on here and I realize that my program will have memory leaks. Using one of the specialized ptrs from boost:: will not be available for me to use. Right now, I'm more concerned with getting the foundation of my program built. That way I can actually get down to the functionality I need to create. Thanks.

    Read the article

  • how to double buffer in multiple classes with java

    - by kdavis8
    I am creating a Java 2D video game. I can load graphics just fine, but when it gets into double buffering I have issues. My source code package myPackage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GameView extends JFrame { private BufferedImage backbuffer; private Graphics2D g2d; public GameView() { setBounds(0, 0, 500, 500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backbuffer = new BufferedImage(getHeight(), getWidth(), BufferedImage.TYPE_INT_BGR); g2d = backbuffer.createGraphics(); Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.getImage(this.getClass().getResource("cage.png")); g2d.setColor(Color.red); //g2d.drawString("Hello",100,100); g2d.drawImage(img, 100, 100, this); repaint(); } public static void main(String args[]) { new GameView(); } public void paint(Graphics g) { g2d = (Graphics2D)g; g2d.drawImage(backbuffer, 0, 0, this); } }

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >