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

Sunday, October 23, 2022

[FIXED] How to send class equals implementation to client using a WCF Web Server

 October 23, 2022     c#, datamember, java-client, wcf, webserver     No comments   

Issue

I'm developing an aplication in java (JSF) which communicates whith an WCF web server. I developed the webserver using c#, and I'm havin trouble to send the equals implementation of an complex object to the java client. For example, consider this c# class:

[DataContract(Namespace = "http://mywebservice.com/Entidades")]
    public class Record{private Int64 id;
    [DataMember]
    public Int64 Id
    {
        get { return id; }
        set { id = value; }
    }

    public override bool Equals(Object obj)
    {
          if(obj is Record){
               Record rec = obj as Record;
               return rec.Id == this.Id;
         }
         return false;
    }

}

First tryed to put the [DataMember] in the equals, but I discovered that I can't do that. How is the right way to send this implementation of the "equals" of this complex type to the java client?

Thanks in advance


Solution

That doesn't make sense.
Web services transfer data, not code.

You need to implement equals() in you Java objects in source.



Answered By - SLaks
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does it mean to put DataMemberAttribute on interface member?

 October 23, 2022     c#, datacontract, datamember, interface     No comments   

Issue

What does it mean to put a DataMemberAttribute on an interface member? How does this affect derived classes?


Solution

As shown in the following signature, the DataMember attribute is not inheritable

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, Inherited = false, 
    AllowMultiple = false)]
public sealed class DataMemberAttribute : Attribute

Therefore, it makes very little sense to decorate interface members with this attribute as you will have to decorate the implementing classes' members with this attribute too.



Answered By - vc 74
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I make 2 c++ classes know about each other's data members?

 October 23, 2022     c++, class, datamember, iterator     No comments   

Issue

My assignment is to make a class that acts like a standard library List. I am unable to get the iterator to work properly, because it must access the tail of the linked list when decrementing from the end. Here is a section of my header file:

typedef int T;//for now; eventually will be templated
class list;//**forward declaration, doesn't let other classes know about _tail.**
class Node
{
    //this works fine; class definition removed to make post shorter
};
class list_iterator
{
    private:
        Node* _node;
        list* _list;
    public:
        //constructor
        list_iterator& operator--(){_node=_node?(_node->_prev):(_list->_tail);return *this;}
        //some other declarations
};
class list
{
    friend class list_iterator;
    private:
        Node/*<T>*/ *_head,***_tail**;
        int _size;
    public:
        typedef list_iterator iterator;
        //some constructors and other method declarations
        iterator begin() const {iterator it(_head);return it;}
        iterator end() const {iterator it(0);return it;}
        //more method declarations
};

I tried to bold the important parts, but it is just surrounding them with asterisks. NOTE: Most of the member functions are defined in the cpp file; they all happen to be removed for a short post.


Solution

You just need to move the method definition of operator-- out of the class and put it after list (or in the source file (probably a better idea. Leave the header file for declarations)).

Note: Leave the declaration inside list_iterator

class list_iterator
{
    /* STUFF */
    list_iterator& operator--();
 };
class list
{ 
     /*  STUFF */ 
};

// Now list_iterator::operator-- can see all the members of list.
list_iterator& list_iterator::operator--()
{
    _node=_node?(_node->_prev):(_list->_tail);
    return *this;
}

Unlike what some other answers suggest. Friendship does NOT break encapsulation. In fact in increases encapsulation (when done correctly) by making the friend part of the classes interface. It does however tightly bind the friend to the class.

This is exactly what you want for iterators. For the iterator to work efficiently it needs to know the internals of the class so it is usually a friend (or an internal class). It increases the usability of the class without exposing the internal workings of the class at the cost that it tightly couples the iterator to the class (so if you change the class you will need to change the implementation of the iterator (but this is not unexpected)).



Answered By - Martin York
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] how to WCF dynamic DataMember?

 October 20, 2022     datacontract, datamember, json, wcf     No comments   

Issue

example: a Customer class have 100 data member(id, name, age, address...etc) to be serialization to JSON.

In Config file such as Web.config, can set a output list to serialize JSON ouptut.

If output only id and name, then JSON only have id and name.

My Question: Can support dynamic DataMember in a DataContract ?


Solution

You mean optional datamembers, I guess so, check this question Surely you'll have to have null values for the ones you dont want to send over the wire. Another, more dirtier, solution would be to use a dictionary as a datamember and have the fields you want to send as elements there. There may be type conversion issues, but maybe it serves you better.

Edit:

You probably want to go with a dictioray serialized as an associative array en js, as this question specifies. Check the answers and the links in there. That should get you going. But still I'd go with optional datamembers since it's more of a "contract" thing. Other than that a better description of what you want to do will help.



Answered By - Carlos Grappa
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get names of all private data members in a class

 October 20, 2022     class, datamember, java, private     No comments   

Issue

I need a function that will return the names of all the private data members in my class as strings (perhaps in an array or list?), where each string is the name of a private, non final data member in my class. The non final condition is optional, but it would be nice.

1) Is this even possible? I think there is a way to retrieve all method names in a class, so I think this is possible as well.

2) I know I am asking for a hand out, but how do I do this?

EDIT

I have NO idea where to begin.

It seems java.lang.reflect is a good place to begin. I have started researching there.


Solution

This should do the trick. Basically you got in a List all the fields of your class, and you remove the one who are not private. :

public static void main(String [] args){
    List<Field> list = new ArrayList<>(Arrays.asList(A.class.getDeclaredFields()));

    for(Iterator<Field> i = list.iterator(); i.hasNext();){
        Field f = i.next();
        if(f.getModifiers() != Modifier.PRIVATE)
            i.remove();
    }
    for(Field f : list)
        System.out.println(f.getName());
}

Output :

fieldOne
fieldTwo

Class A :

class A {
    private String fieldOne;
    private String fieldTwo;

    private final String fieldFinal = null;

    public char c;
    public static int staticField;
    protected Long protectedField;
    public String field;
}


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

[FIXED] How do I override a name in JSON returned by ASP.NET

 October 20, 2022     asp.net-web-api, datamember, json     No comments   

Issue

I have the following code in an ASP.NET Web API 2 app:

[DataMember(Name = "override")]
public bool? _override;

But the JSON I receive has that member named _override, not override. How can I change the naming in the JSON?


Solution

As asp.Net web API 2 uses Json.NET internally for json serialization/deserialization,

JsonProperty attribute can be used to override property name on serialization.

so [JsonProperty(PropertyName = "override")] should do the trick.

Thanks.



Answered By - shakib
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How does compiler know how other .cpp files use a static const member?

 October 20, 2022     c++, constants, datamember, initialization, static     No comments   

Issue

Could someone please explain me this example from the most authoritative ISO C++ FAQ? The code goes like this:

// Fred.h
class Fred {
public:
  static const int maximum = 42;
  // ...
};

// Fred.cpp
#include "Fred.h"
const int Fred::maximum;
// ...

And the statement I can't get is:

If you ever take the address of Fred::maximum, such as passing it by reference or explicitly saying &Fred::maximum, the compiler will make sure it has a unique address. If not, Fred::maximum won’t even take up space in your process’s static data area.

Compiler processes .cpp files separately and does not know what other files do with data defined in the one currently being processed. So, how can compiler decide if it should allocate a unique address or not?

The original item is here: https://isocpp.org/wiki/faq/ctors#static-const-with-initializers


Solution

The FAQ entry says that const int Fred::maximum; must be defined in exactly one compilation unit. However, this is only true if the variable is odr-used by the program (for example, if a reference is bound to it).

If the variable is not odr-used then the definition can be omitted.

However, if the variable is actually odr-used but has no definition, then it is undefined behaviour with no diagnostic required. Typically, if the variable's address is required but the definition was omitted, a good quality linker would omit an "undefined reference" error.

But you don't always want to be relying on particular manifestations of undefined behaviour. So it is good practice to always include the definition const int Fred::maximum;.


The quoted paragraph in your question is meant to address a potential programmer concern: "Well, can't I save 4 bytes in my static data area by omitting the definition in some cases?"

It is saying that the compiler/linker could perform whole program analysis, and make its own optimization decision to omit the definition once it has determined that the definition was not used.

Even though the line const int Fred::maximum; is defined as allocating memory for an int, this is a permitted optimization because there is no way that a conforming program could measure whether or not memory had actually been allocated for the int which is not odr-used.

The author of that FAQ entry clearly expects that a compiler/linker would in fact do this.


The wording in the Standard about odr-use is designed to support the following model of compilation/linking:

  • If some code requires the variable to have an address, the object file will contain a reference to the variable.
  • Optimization may remove some code paths that are never called, etc.
  • At link-time, when these references are resolved, that reference will be bound to the definition of the variable.

It does not require the compiler to produce an "undefined reference" error message because this would make it harder for compilers to optimize. Another stage of optimization might happen to entirely remove the part of the object file containing the reference. For example, if it turned out the odr-use only ever occurred in a function that was never called.



Answered By - M.M
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is using [DataMember(EmitDefaultValue = false)] not recommended?

 October 20, 2022     datacontract, datamember, msdn, wcf     No comments   

Issue

In WCF you can define a contract using the [DataContract] and [DataMember] attributes, like this:

[DataContract]
public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}

This article on the MSDN states that using EmitDefaultValue = false is not recommended:

snippet

However, i like to use this, because the XML that is generated using this construction is cleaner. Not specifying this setting results in:

<Sample>
    <Test xsi:nil="true"/>
</Sample>

while using the setting the element is ommited when there is no value:

<Sample>
</Sample>

I'm curious to what the reasoning behind that statement is. Specifically since both snipptes of XML look equivalent to me (and both last part can be deserialized correctly for this contract).

What is the reasoning behind this statement?


Solution

The reason is at the bottom of the article that you link to. The short version is:

  • When the EmitDefaultValue is set to false, it is represented in the schema as an annotation specific to Windows Communication Foundation (WCF). There is no interoperable way to represent this information. In particular, the "default" attribute in the schema is not used for this purpose, the minOccurs attribute is affected only by the IsRequired setting, and the nillable attribute is affected only by the type of the data member.

  • The actual default value to use is not present in the schema. It is up to the receiving endpoint to appropriately interpret a missing element.



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

[FIXED] When passing an data member array into a recursive procedure, is a new copy of that array created in each stack frame?

 October 20, 2022     c++, class, datamember, recursion, stack-frame     No comments   

Issue

I am facing the issue that copy of an 2 dimensional array is not made in each stack frame of recursive call. I am doing indirect recursion.

I also tried sending my data in function call from main() function but the copy was not made. Same address was used in every recursive call.

class board
{


public:

    int board_arr[8][8];

public:
    board()
    {

    }

    void player1Turn()
    {

        for (int i = 0; i < rowCount; i++)
        {
            for(int j = 0; j < rowCount; j ++ )
            {
                if (board_arr[i][j] == 1)
                {
                    //checking if the pawn can move anywhere
                    if (i + 1 <=7 && j - 1 >= 0 && board_arr[i + 1][j - 1] == 0 )
                    {
                        board_arr[i][j] = 0;
                        board_arr[i + 1][j - 1] = 1;

                        player2Turn();

                    }
                    if (i + 1 <=7 && j + 1 <= 7 && board_arr[i + 1][j + 1] == 0)
                    {
                        board_arr[i][j] = 0;
                        board_arr[i + 1][j + 1] = 1;


                        player2Turn();

                    }
                    //opponent infront 
                    //killing
                    //if opponent is infront and checking if you can kill it or not
                    if (i + 2 <= 7
                        && i + 1 <= 7 
                        && j - 2 >=0 

                        && j - 1 >= 0 
                        && board_arr[i + 1][j - 1] == 2
                        && (board_arr[i + 2][j - 2]==0)) 
                    {
                            board_arr[i][j] = 0;
                            board_arr[i + 2][j - 2] = 1;
                            board_arr[i + 1][j - 1] = 0;

                            cout << endl << "kill by p1 " << endl;


                            player2Turn();

                    }
                    if (i + 2 <= 7 
                        && i + 1 <= 7 
                        && j + 2 <= 7

                        && j + 1 <=7 
                        && board_arr[i + 1][j + 1] == 2 
                        && (board_arr[i + 2][j + 2]==0))
                    {
                        board_arr[i][j] = 0;
                        board_arr[i + 1][j + 1] = 0;
                        board_arr[i + 2][j + 2] = 1;


                        cout << endl << "kill by p1 " << endl;

                        player2Turn();

                    }
                }

            }

        }

    }
    void player2Turn()
    {

        for (int i = rowCount-1; i >= 0; i--)
        {
            for (int j = rowCount-1; j >= 0; j--)
            {
                if (board_arr[i][j] == 2)
                {
                    //checking if the pawn can move anywhere
                    if (i - 1 >= 0 && j - 1 >= 0 && board_arr[i - 1][j - 1] == 0)
                    {
                        board_arr[i][j] = 0;
                        board_arr[i - 1][j - 1] = 2;


                        player1Turn();

                    }
                    if (i - 1 >= 0 && j + 1 <=7 && board_arr[i - 1][j + 1] == 0)
                    {
                        board_arr[i][j] = 0;
                        board_arr[i - 1][j + 1] = 2;


                        player1Turn();

                    }
                    //opponent infront 
                    //killing
                    //if opponent is infront and checking if you can kill it or not
                     if (i - 2 >= 0
                        && i - 1 >= 0
                        && j - 2 >= 0

                        && j - 1 >= 0
                        && board_arr[i - 1][j - 1] == 1
                        && (board_arr[i - 2][j - 2] ==0))
                    {
                        board_arr[i][j] = 0;
                        board_arr[i - 2][j - 2] = 2;
                        board_arr[i - 1][j - 1] = 0;

                        cout << endl << "kill by p2 " << endl;

                        player1Turn();



                    }
                    if (i + 2 <= 7
                        && i - 1 >= 0
                        && j + 2 <=7

                        && j + 1 <= 7
                        && board_arr[i - 1][j + 1] == 1
                        && (board_arr[i - 2][j + 2] ==0))
                    {
                        board_arr[i][j] = 0;
                        board_arr[i - 2][j + 2] = 1;
                        board_arr[i - 1][j + 1] = 0;

                        cout << endl << "kill by p1 " << endl;

                        player1Turn();

                    }
                }

            }

        }
    }

};

same copy of the board_arr was used in each call.


Solution

You are not passing board_arr to a recursive method, that is those methods do not have that array in their parameters. So board_arr is not being copied.

Because those methods are instance methods of board class, everything is passed in each method call is this pointer to the instance of board.



Answered By - Renat
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where is local variable of member function created if object is created via new?

 October 20, 2022     c++, class, datamember     No comments   

Issue

Class A
{
    int a;
    int get_a()
    {
       int d;
       return a;
    }
};

A* obj_a_ptr = new A;
int c = A->get_a();

Where is int d memory allocated , in heap or stack ?


Solution

Member functions are not that different from free functions, they only implicitly get a this pointer as first parameter. So your member function is more or less equivalent to (lets forget about the fact that nothing in your A is actually accesible, because it is all private)

int get_a(A* obj)
{
   int d;
   return obj->a;
}

I hope this already answers your question. Whether obj was allocated via new or not makes no difference for d being on the stack.



Answered By - 463035818_is_not_a_number
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is handy way to modify the private class data members without writing explicit setters? Are templates useful?

 October 20, 2022     c++, c++14, datamember, private, templates     No comments   

Issue

I have a class with data members.

class Sph
{
public:
    Sph( float radius , float segments , const Shader& shader );
    Sph(const Sph& geometry);
    Sph& operator = (const Sph& geometry);
    ~Sph();
    void init();
    void CleanUp();
    void draw();
    void CreateUI(QFormLayout* layout);
    std::vector< Sum_Vertices > GetVertices();

private:
    float Radius,Segments;
    bool isInited;
    unsigned int m_VAO, m_VBO , m_IBO;
    int iNumsToDraw;
    bool isChanged;
    Shader shader;
    int indexCount;
};

in order to change the data of the class I have to write individual methods.

void SetRadius( float radius )
{
   this->Radius = radius;
}

Is it possible to write a templated function which can change different data members of the class?


Solution

Since the variables are different by names, the template may not help here.


This is a classic case, where you can use macros to your advantage & ease.

Definition:

#define GET_SET(X) X; \ 
    public: const decltype(X)& get_##X() const { return X; } \ 
            void set_##X(const decltype(X)& value) { X = value; } private:

Utility:

class Sph
{
   ...
private:
  float GET_SET(Radius);
  float GET_SET(Segments);
  ...
};

Usage:

Sph sph;
sph.set_Radius(3.3);
cout << sph.get_Radius() << "\n";

Demo.



Answered By - iammilind
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do pointers to members in C++ work internally?

 October 20, 2022     c++, datamember, pointers     No comments   

Issue

I am trying to know how pointers to members work in C++.

I looked at some places, and found that they store some sort of offset. And use the fact that members occur in memory in the same order in which they are declared in the class/structure definition.But...

#include <iostream>
#include<typeinfo>
using namespace std;
struct S
{
    S(int n): mi(n) {}
    int mi;
    int k;
    int f()  {return mi+k;}
};

int main()
{
    S s(7);
    int S::*pmi = &S::mi;
    int S::*lop = &S::k;
    int (S::*sf)() = &S::f;
    cout<<&S::mi<<endl<<&S::k<<endl<<&S::f<<endl<<pmi<<endl<<lop<<endl<<sf<<endl;
    cout<<typeid(lop).name()<<endl;
}

I expected to see some sort of offsets. But, all values in the first line with cout<< , gave 1 as output.

I don't understand , if all are giving 1, where is the information regarding offsets being stored?

It'd be really helpful if you can explain what is really going on.


Solution

Iostreams insertion operator does not have an overload for pointers to members.

There is however an overload for bool, and pointers to members are implicitly convertible to bool - a null pointer to member is converted to false, otherwise true. bool is streamed as 1 if true and 0 if false. So the output that you're observing is the fact that none of your pointers to members are null.

I tried incrementing by ++.. but that too doesn't work..

Incrementing doesn't work because pointers to members don't support pointer arithmetic.

So , is there any way of actually seeing the offset values?

Anything can be observed as a byte array, so you can marvel at the contents of the member pointers with a little helper function:

template<class T>
void print_raw(const T& obj) {
    const unsigned char* cptr = reinterpret_cast<const unsigned char*>(&obj);
    const unsigned char* end = cptr + sizeof(T);
    while(cptr < end) {
        printf("%02hhx ", *cptr++); // is there simple way with iostreams?
    }
    std::cout << '\n';
}

std::cout << "pmi: ";
print_raw(pmi);
std::cout << "lop: ";
print_raw(lop);
std::cout << "sf:  ";
print_raw(sf);

Example output on my system:

pmi: 00 00 00 00 00 00 00 00 
lop: 04 00 00 00 00 00 00 00 
sf:  f0 08 40 00 00 00 00 00 00 00 00 00 00 00 00 00 

This may give you some insight about how the compiler has implemented them. Note that if the implementation includes any padding bytes / bits, those could have any value and thus any non-zero value may be meaningless.

The member object pointer output seems quite obvious. It looks like a little endian 64 bit offset into the object. mi is at offset 0 and k is offset 4 bytes.



Answered By - eerorika
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to initialize static const member that is array of another class, and use it?

 October 20, 2022     arrays, c++, datamember, static-initialization     No comments   

Issue

I am trying to instantiate a vending machine with in inventory. The inventory I planned to be an array of class Drinks. Here is what I have written so far.

VendingMachine.h - should contain array of Drinks class

#include "Drinks.h"

class VendingMachine {
   private:
      static const int NUM_DRINKS = 5;
      static const Drinks drinks[NUM_DRINKS];
   public:
      VendingMachine();
};

Now Drinks.h

#include <string>

class Drinks {
   private:
      std::string name;
      double price;
      int qtyInMachine;
   public:
      Drinks(std::string name, double price, int qtyInMachine);
      void decrementQuantity();
};

VendingMachine.cpp

#include "VendingMachine.h"

VendingMachine::VendingMachine() {
}

Drinks.cpp

#include <string>
#include "Drinks.h"

Drinks::Drinks(std::string n, double p, int qty) : name(n), price(p), qtyInMachine(qty) {
}
void Drinks::decrementQuantity() {
   qtyInMachine--;
}

Now for test program

#include <iostream>
#include "VendingMachine.h"

const Drinks VendingMachine::drinks[VendingMachine::NUM_DRINKS] {Drinks("Cola",1.25,20),
      Drinks("Root Beer",1.35,20),Drinks("Orange Soda",1.20,20),Drinks("Grape Soda",1.20,20),
      Drinks("Bottled Water",1.55,20)};

int main() {
   VendingMachine vm1;
   for (int i = 0; i < VendingMachine::NUM_DRINKS; i++) {
      std::cout << vm1.drinks[i].name << " ";
   }
}

The line where I define drinks the compiler complains that it is not an integral const-expression and that VendingMachine::NUM_DRINKS is private in the context. It claims the same private context error for my for statement with NUM_DRINKS, also in my cout statement it claims the same for both drinks and name. I need to know how and where to initialize drinks and how to use in main without getting the 'private in this context' errors.

As I am an extreme beginner with classes and OO in general, I cannot find my error. Any assistance is greatly appreciated.


Solution

Actually, you need to study / revise the OOP concepts of encapsulation and data-hiding along with the C++ specific features of access specifiers (private and public) and how they're used and in what context.

Note: There's a protected access specifier also, you'd study it in inheritance topic.

  • public part of a class is visible to the outside world e.g. other classes, functions, etc.
  • private is accessible only within the class itself.

You have private members that you're accessing in a public context that's why you're getting these errors i.e.:

class VendingMachine {
   private:
      static const int NUM_DRINKS = 5;          // private to class
      static const Drinks drinks[NUM_DRINKS];   // private to class
   public:
      VendingMachine(){}
};

and, in main function:

int main() {
   VendingMachine vm1;
   for (int i = 0; i < VendingMachine::NUM_DRINKS; i++) { // accessing private member VendingMachine::NUM_DRINKS
      std::cout << vm1.drinks[i].name << " ";             // accessing private members vm1.drinks[i].name
   }
}

The name data member is private to Drinks class and you're accessing it publicly in main.

These are the issues with that you need to fix.

For accessing a private data member, usually an accessor function is used such as to access name you'd have a public getName() method and so on.

  • To access private instance data members, you'd need public methods.
  • To access private static data members or class members, you'd need public static member functions.

Another thing that I'd like to point is this:

// Declaration: Observe names of the method arguments
Drinks(std::string name, double price, int qtyInMachine); 

// Definition: Observe the names of the arguments here 
Drinks::Drinks(std::string n, double p, int qty) : name(n), price(p), qtyInMachine(qty) {
}

In a separate interface/implementation scenario as it is now, it doesn't matter. But, if you would need to move the definition in the class later you'd have to make them consistent then. So, it's a maintenance overhead in the long run.


Here's a minimal modified working example: http://ideone.com/tr5oZu



Answered By - Azeem
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What if an argument has the same name as that of a data member?

 October 20, 2022     c++, class, datamember, namespaces, standards     No comments   

Issue

#include <iostream>

struct A
{
    A(int n) { std::cout << n; }
    int n{2};
};

int main()
{
    A a{1};
}

The output is 1 rather than 2.

Does the C++ standard define that the argument name is preferred if it is the same as that of a data member?


Solution

The argument is in a "closer" scope than the member variable, so the argument shadows the member variable.

The obvious solution is to rename the argument (or the member variable), so they are not the same anymore.

You can also use this->n to explicitly use the member variable.



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

[FIXED] How to have C# interface with readonly member

 October 20, 2022     c#, datamember, interface, protected     No comments   

Issue

Interface inconvenience

I recently found myself in need of something, which should very much be possible in C# (I know it is in C++): Several classes need an api key, which absolutely has to be a private, immutable field (except for being declared in the constructor). To avoid code duplication, I wanted to create an interface for classes that need an api key.

I will let the code speak for itself:

public interface IHasApiKey
{
    protected readonly string _apiKey = String.Empty;
}

Problems:

  • I could let it be a class instead, since interfaces cannot instantiate member attributes. But since C# does not allow multiple inheritance, and since I consider this feature a behaviour rather than an implementation, I can't see why it shouldn't be an interface. And it might clash with classes which already have a base class.
  • I could convert it into a property, but no matter the accessibility level, if it is inherited, it can still be modified in methods of derived classes, whereas I really want the behaviour of readonly. (const, but can be set in the constructor)
  • I discovered the attribute System.ComponentModel.ReadOnlyAttribute, but documentation is very limited, and it doesn't look like it performs like readonly, but more like an attribute which can be queried for in user code.
  • If I convert it to an auto-property, then all derived classes need to specify a private data member to point to, which again means duplicate code (which I try to avoid by having this interface in the first place)

For completeness' sake, here is what I imagine the correct code would look like in C++:

class IHasApiKey
{
private:
    std::string _apiKey = "";
protected:
    IHasApiKey(const std::string& apiKey) : _apiKey(apiKey) {}

    // tbo, I'm not quite sure about how to optimally write this one,
    // but the idea is the same: provide protected read access.
    const std::string& GetKey() { return const_cast<std::string&>(_apiKey); }
};

Do I explain properly? And does anyone have an idea of how to solve this elegantly? Thanks a lot in advance.


Solution

Update [Closed]

It seems I am limited by my choice of language. C# has no way of accomplishing what I want. The best thing would be allow decorating the interface's setter:

public interface IHasApiKey
{
    protected string _apiKey { get; readonly set; }
}

But likely that would require impossible changes to the compiler, and likely break with the language design. I find it unlikely that it will ever be added.

Thank you everyone who took their time to think about this!



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

[FIXED] Why is compiler throwing "expected a type specifier"?

 October 20, 2022     c++, class, datamember, initialization, visual-studio     No comments   

Issue

class A
{
private:
   int a;

public:
   int get_a()
   {
      return a;
   }
   A(int mode)
   {
      a = 0;
   }
   A()
   {
      a = 5;
   }
};

class B
{
public:
   A b(0);   
};

class C
{
   int c;

public:
   C(int mode)
   {
      c = 0;
   }
   C()
   {
      c = 1;
   }
};

int main()
{
   B bb;
   C cc(0);
   //cout << bb.b.get_a();
   system("pause");
   return 0;
}

if im using () brackets on b in class B it gives the error if i switch to {} everything is fine . My question is shouldn't i be allowed to do that since on cc in main it doesn't give any error. And im allowed to use () brackets when initializing objects.


Solution

According to the C++ 20 Standard (11.4 Class members) you may use a brace-or-equal-initializer to initialize a data member of a class

member-declarator:
    ...
    declarator brace-or-equal-initializeropt

So you may use either

class B
{
public:
   A b = 0;   
};

or

class B
{
public:
   A b { 0 };   
};

This allows to avoid an ambiguity with a function declaration.



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

[FIXED] Why is my inherited method outputting Base class' member instead of derived class' member

 October 20, 2022     c++, datamember, inheritance     No comments   

Issue

I am trying to print the member 'age' from the Mum class which inherits the method print_age() from Dad, but it is printing the member 'age' from Dad's class

#include <iostream>
#include <string>

using namespace std;

int main()
{

  class Dad
  {
  protected:
    int age = 59;

  public:
    void print_age() { cout << age << endl; }
  };

  class Mum : public Dad
  {
  protected:
    int age = 54;
  };

  Mum m;
  m.print_age();
}

This outputs 59 when I want it to output 54


Solution

In C++, only member functions can be overridden, not member variables. As a result, when you write

  class Mum : public Dad
  {
  protected:
    int age = 54;
  };

C++ interprets this as "I know that Dad already has an int field called age whose value is 59, but I'd like to also add a different int field called age whose value is 59 and that only lives in the Mum class." Stated differently, you aren't replacing the old value of age with a new one; you're declaring a new variable that Dad doesn't know about that coincidentally has the same name as one of the variables from Dad.

Now, why does that mean that you see the value 59? Let's look at the code for Dad:

  class Dad
  {
  protected:
    int age = 59;

  public:
    void print_age() { cout << age << endl; }
  };

In print_age, C++ sees the use of age and then needs to decide what to do. It has no idea that there's a Mum class that will be defined later that will also independently create a protected int called age. Rather, it sees age defined in Dad and says "oh, that must be what age refers to" and uses that value. As a result, when you call

   m.print_age();

you see the value of age in Dad rather than the value of age in Mum. It's because the code for print_age is written in the Dad class, which can't see anything in Mum.

If you'd like to make it so that Mum has age 59, you could do this instead:

  class Mum : public Dad
  {
  public:
     Mum() {
        age = 54;
     }
  };

Here, the constructor says "when you create a Mum object, go find the age data member and set it equal to 54." This means that there's one single age variable, which defaults to 59 but is explicitly set to 54 in the Mum constructor. Now, calling print_age will print out 54 because the code for Dad::print_age looks at the age variable that was just set.

Hope this helps!



Answered By - templatetypedef
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why C++ non-static data members require unique addresses?

 October 20, 2022     attributes, c++20, datamember     No comments   

Issue

Recently C++ has added the feature [[no_unique_address]] for empty data types such as struct empty {};.

How do empty data memberes benefit from having a unique address?

Why wouldn't the standard make all empty data members address-less?

Why C++ non-static data members require unique addresses?


Solution

Because (among other things), that's how C does it. If C++ was to be able to be layout-compatible with C, then an empty NSDM of a C++ struct would have to take up the same space as an equivalent C declaration.

Empty base class optimization was able to be added to C++ because base classes aren't C language features, so there was never any question about compatibility with C. If you want to allow empty member optimization, you have to have the C++ programmer be explicit about whether they want to make the optimization available (and therefore, the type isn't directly compatible to a C type). You can't just spring it on them.



Answered By - Nicol Bolas
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to access class private data members in method parameter of class , i get an error invalid use of non static data members

 October 20, 2022     c++, class, datamember, methods, oop     No comments   

Issue

i have two classes Node and AvlTree , i will make other methods of AvlTree later but i can't access root data member of AvlTree in it's own class , how can i access root in AvlTree class inOrder method.

My code is following here

class Node {
    public:
        int key;
        Node* left;
        Node* right;
        int height;

        Node(int key) : key(key) , left(nullptr) , right(nullptr) , height(1) {};
};

class AvlTree {
    private:
        Node* root;
    public:
        AvlTree() : root(nullptr) {};

        int height(Node* ptr) {
            
        }

        int getBalanceFactor(Node* ptr) {
            
        }

        void inOrder(Node* itr = root) {      // <--- i get an error here

        }
};

I tried with this->root but that also does't work , what i am do wrong here , also can i not access like this in it's own class. I got an error like

09_avl_tree.cpp:36:34: error: invalid use of non-static data member ‘AvlTree::root’
   36 |         void inOrder(Node* itr = root) {
      |                                  ^~~~
09_avl_tree.cpp:15:15: note: declared here
   15 |         Node* root;
      |               ^~~~

I don't want to make root as static data member. because i want multiple instances of AvlTree.


Solution

The short answer, as the compiler is telling you, is that you can't do that as a default value of an argument.

The simplest approach would be to overload the inOrder() function, for example (within the definition of AvlTree)

  void inOrder(Node *itr)
  {
        // whatever
  }

  void inOrder()
  {
       inOrder(root);
  }
  

Also, unrelated to your question, the shadowing of member names in Nodes constructor (e.g. an argument named key used to initialise a member named key) is not a good idea, since it is easy to mislead human readers about what the code does. It is therefore often considered preferable to name the argument differently from the member.



Answered By - Peter
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the difference between assigning an instance variable before and after parameter?

 October 20, 2022     datamember, function, java, oop     No comments   

Issue

What is the difference between assigning a parameter to an instance variable? Why is it wrong when you write the parameter before the instance variable?

int variable; 

void set(int parameter)
{
    variable = parameter;
    parameter = variable; 
}

Solution

Case 1:

int variable;

void set(int parameter)
{
    variable = parameter;
}

Case 2:

int variable;

void set(int parameter)
{
    parameter = variable;
}

Both cases are correct by Java syntax, but case 2 has very little logical value...

The case 2 method parameter has a value and we need to use it. but before using this value, we change this by assigning variable, so we lost the previous value.



Answered By - Istiaque Hossain
Answer Checked By - Senaida (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