PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label data-members. Show all posts
Showing posts with label data-members. Show all posts

Thursday, October 20, 2022

[FIXED] How to write members of a class to a binary file using cpp?

 October 20, 2022     binaryfiles, c++, class, data-members     No comments   

Issue

I'm writing a small back-end in cpp where I have to write some crossword data into a binary file. I have created an XWPuzzle class with all its data members public, and xWord is an object of this class. Here is the piece of code with which I'm trying to write to the binary file:

#include"binIncludes.h"

int main(int argc, char** argv)
{
    cout<<"Bin read-write Tester\n";
    xWord.title="Yeah!\0";
    xWord.author="Nobody\0";
    xWord.grid=147;
    xWord.userGrid=109;
    xWord.clues[0]="as\0";
    xWord.clues[1]="de\0";
    xWord.clues[2]="re\0";
    xWord.solution[0]="ASSET\0";
    xWord.solution[1]="DEER\0";
    xWord.solution[2]="REED\0";
    xWord.checksum=(int)(xWord.title.at(0))+(int)(xWord.author.at(0))+xWord.grid+xWord.userGrid;
    xWord.checksum+=(int)(xWord.clues[0].at(0))+(int)(xWord.clues[1].at(0))+(int)(xWord.clues[2].at(0));
    xWord.checksum+=(int)(xWord.solution[0].at(0))+(int)(xWord.solution[1].at(0))+(int)(xWord.solution[2].at(0));
    fstream file;
    file.open("binTest.bin",ios::out|ios::binary);
    file.write(SIGNATURE,sizeof(SIGNATURE));
    file.write(VERSION,sizeof(VERSION));
    file.write(TYPE,sizeof(TYPE));
    file.write((char*)xWord.checksum,sizeof(xWord.checksum));
    file.write(xWord.title.c_str(),xWord.title.size());
    file.write(xWord.author.c_str(),xWord.author.size());
    file.write((char*)xWord.grid,sizeof(xWord.grid));
    file.write((char*)xWord.userGrid,sizeof(xWord.userGrid));
    file.close();
    cout<<"File written\n";
    _getch();
    return 0;
}

SIGNATURE, VERSION and TYPE are null-terminated strings, but the compiled program throws an error when it gets to the line

file.write((char*)xWord.checksum,sizeof(xWord.checksum));

The debugger throws a First-chance exception (Access Violation reading location error) at MSVCR100.dll. Am I doing something wrong by using a member of a class the wrong way? This is an independent project and not any homework. I've been running around for this for two days now. Any specific help appreciated. Thanks.

I have other data to be written also, in addition to those from this class.

EDIT:

XWPuzzle.h:

#ifndef XWPULZZLE_H
#define XWPUZZLE_H

#include"binIncludes.h"

class XWPuzzle
{
    public:
        string title;
        string author;
        int grid;
        int userGrid;
        string clues[3];
        string solution[3];
        int checksum;
} xWord;

#endif

binDefines.h:

#ifndef BIN_DEFINES_H
#define BIN_DEFINES_H

#include"binIncludes.h"

#define SIGNATURE "BinFile\0"
#define VERSION "0.1.1\0"
#define TYPE "With Solution\0"

#endif

binIncludes.h:

#ifndef BIN_INCLUDES_H
#define BIN_INCLUDES_H

#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>

using namespace std;

#include"binDefines.h"
#include"XWPuzzle.h"

#endif

Solution

You are casting integer to a pointer and trying to write data by this pointer. That's wrong. You shoud get pointer to a checksum, cast it and then write

file.write((char*)(&xWord.checksum),sizeof(xWord.checksum));

Same with grid and userGrid fields



Answered By - Jeka
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to specify member pointer to an array element?

 October 20, 2022     arrays, c++, data-members, pointers     No comments   

Issue

I have a library with function, which looks like this:

template<typename S1> void NastyFunction(S1 *array, EntryType S1::* member1);

So if I have an array of structs like:

struct TData {
  float a;
  float b[10];
};

TData dataArray[N];

I can apply NastyFunction to all a-s in dataArray using:

NastyFunction( dataArray, &TData::a );

How to apply this NastyFunction to all for example b[7]-s in dataArray?


Solution

You can't. While the entire array is a member of the class, its individual elements are not, so there is no way to make a member pointer point at them.



Answered By - Angew is no longer proud of SO
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is a reasonable way of keeping track of multiple windows in PyQt?

 October 20, 2022     data-members, pyqt, windows     No comments   

Issue

I'm writing a PyQt application that shall feature multiple windows. Right now, I am interested in having one of two windows open at a time (so a click of a button in one window causes a switch to the other window). What is a reasonable way of keeping track of multiple windows in a PyQt application? My initial attempt, as shown below, essentially stores instances of the QtGui.QWidget in data members of a global instance of a simple class.

I'm new to PyQt. Is there a better way to approach this?

#!/usr/bin/env python

import sys
from PyQt4 import QtGui

class Program(object):
    def __init__(
        self,
        parent = None
        ):
        self.interface = Interface1()

class Interface1(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface1, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 1')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface2()

class Interface2(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface2, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 2')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface1()

def main():
    application = QtGui.QApplication(sys.argv)
    application.setApplicationName('application')
    global program
    program = Program()
    sys.exit(application.exec_())

if __name__ == "__main__":
    main()

Solution

Have a single main window with a QStackedWidget to hold the different interfaces. Then use QStackedWidget.setCurrentIndex to switch between the interfaces.

Also, try to avoid using global references. If you want GUI components to communicate with each other, use signals and slots. You can easily define your own custom signals if there are no suitable built-in ones.



Answered By - ekhumoro
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is a reasonable way of keeping track of multiple windows in PyQt?

 October 20, 2022     data-members, pyqt, windows     No comments   

Issue

I'm writing a PyQt application that shall feature multiple windows. Right now, I am interested in having one of two windows open at a time (so a click of a button in one window causes a switch to the other window). What is a reasonable way of keeping track of multiple windows in a PyQt application? My initial attempt, as shown below, essentially stores instances of the QtGui.QWidget in data members of a global instance of a simple class.

I'm new to PyQt. Is there a better way to approach this?

#!/usr/bin/env python

import sys
from PyQt4 import QtGui

class Program(object):
    def __init__(
        self,
        parent = None
        ):
        self.interface = Interface1()

class Interface1(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface1, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 1')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface2()

class Interface2(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface2, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 2')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface1()

def main():
    application = QtGui.QApplication(sys.argv)
    application.setApplicationName('application')
    global program
    program = Program()
    sys.exit(application.exec_())

if __name__ == "__main__":
    main()

Solution

Have a single main window with a QStackedWidget to hold the different interfaces. Then use QStackedWidget.setCurrentIndex to switch between the interfaces.

Also, try to avoid using global references. If you want GUI components to communicate with each other, use signals and slots. You can easily define your own custom signals if there are no suitable built-in ones.



Answered By - ekhumoro
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why isn't the const qualifier working on pointer members on const objects?

 October 20, 2022     c++, constants, data-members, pointers     No comments   

Issue

I know this has been asked a lot, but the only answers I could find was when the const-ness was actually casted away using (int*) or similar. Why isn't the const qualifier working on pointer type member variables on const objects when no cast is involved?

#include <iostream>

class bar {
public:
    void doit()       { std::cout << "    bar::doit() non-const\n"; }
    void doit() const { std::cout << "    bar::doit() const\n"; }
};

class foo {
    bar* mybar1;
    bar mybar2;
public:
    foo() : mybar1(new bar) {}
    void doit() const {
        std::cout << "foo::doit() const\n";
        std::cout << "  calling mybar1->doit()\n";
        mybar1->doit();  // This calls bar::doit() instead of bar::doit() const
        std::cout << "  calling mybar2.doit()\n";
        mybar2.doit(); // This calls bar::doit() const correctly
    }
    // ... (proper copying elided for brevity)
};

int main(void)
{
    const foo foobar;  // NOTE: foobar is const
    foobar.doit();
}

The code above yields the following output (tested in gcc 4.5.2 and vc100):

foo::doit() const
  calling mybar1->doit()
    bar::doit() non-const         <-- Why ?
  calling mybar2.doit()
    bar::doit() const

Solution

When a foo instance is const, its data members are const too, but this applies differently for pointers than you might at first think:

struct A {
  int *p;
};

A const obj;

The type of obj.p is int * const, not int const *; that is, a constant pointer to int, not a pointer to constant int.

For another way to look at it, let's start with a function:

template<class T>
T const& const_(T const &x) {
  return x;
}

Now imagine we have an A instance, and we make it const. You can imagine that as applying const_ on each data member.

A nc;
// nc.p has type int*.
typedef int *T;  // T is the type of nc.p.

T const &p_when_nc_is_const = const_(nc.p);
// "T const" is "int * const".

const T &be_wary_of_where_you_place_const = const_(nc.p);
// "const T" is "int * const".
// "const T" is *not* "const int *".

The variable be_wary_of_where_you_place_const shows that "adding const" is not the same as prepending "const" to the literal text of a type.



Answered By - Fred Nurk
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When manipulating data members: which of the following is considered best practice

 October 20, 2022     c++, c++11, class, data-members, object     No comments   

Issue

I want to start adopting best practice and have seen class members being manipulated in different ways. I am not aware of any subtle nor significant differences in the following example.

I wish to clarify an optimal approach if any of the two or another suggestion.

const Fraction & Fraction::timesEq(const Fraction & f) {

  //First approach
  numerator *= f.numerator;
  denominator *= f.denominator;

  //Second approach
  numerator *= f.getNumerator();
  denominator *= f.getDenominator();

  return (*this); //would 'return' statement this be considered best practice?
}

Solution

The second approach survives subclassing and possible virtual redifinitions of the methods if this matters for the particular case but more cumbersome and boring.



Answered By - user3159253
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When to use which data member initialization in C++

 October 20, 2022     c++, class, data-members, initialization     No comments   

Issue

Considering this program:

#include <iostream>

class C
{
public:
    C(void): a(1)
    { a=2; }
    int a{3};
};

int main(void)
{
    C c{};
    std::cout << c.a; // 2
}

I can see three forms of data member initialization:

  1. using a member initializer list
  2. using the Constructor
  3. using a declaration in the class body

When to use which?


Solution

1: Using a declaration in the class body

You should use this when the member will always be initialized with the same value, and it doesn't make sense to have to explicitly write that for each constructor.

2: Using a member initializer list

The member initializer list is obviously necessary for a member that lacks a default constructor, but aside from that, if you're initializing a member based on the constructor, it makes sense to do it here.

3: Using the constructor body

The constructor body is more useful for logic that can't be performed in a single statement (in the init-list). However, I don't think there is much difference between initializing a POD in the member initializer list or the constructor body.



Answered By - Weak to Enuma Elish
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What happens to uninitialized class members in c++?

 October 20, 2022     c++, class, data-members     No comments   

Issue

What happens to uninitialized class members in c++? If I have to do this, what should I take care of?

#include <iostream> 
using namespace std;

class Foo {
    int attr1, attr2;   
public:
    Foo ();

Foo::Foo () {   attr1 = 5; }

Foo myThing(); 

Solution

What happens to uninitialized class members in c++?

They are default initialized, which in case of fundamental types like int means that it will have an indeterminate value.

what should I take care of?

You should take care to never read an indeterminate value.



Answered By - eerorika
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access private data members outside the class without making "friend"s?

 October 20, 2022     c++, class, data-members, encapsulation, private     No comments   

Issue

I have a class A as mentioned below:-

class A{
     int iData;
};

I neither want to create member function nor inherit the above class A nor change the specifier of iData.

My doubts:-

  • How to access iData of an object say obj1 which is an instance of class A?
  • How to change or manipulate the iData of an object obj1?

Note: Don't use friend.


Solution

You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.

(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)



Answered By - Mat
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing